鉴于,
class Foo {
private Long id;
private String name;
private String category;
private List<String> categories;
// getters & setters
}
我有一个物品清单。
final Foo f1 = new Foo(1L, "a", "c1");
final Foo f2 = new Foo(1L, "a", "c2");
final Foo f3 = new Foo(2L, "a", "c1");
final List<Foo> li = List.of(f1, f2, f3);
看起来像
{[Foo [id=1, name=a, category=c1, categories=null], Foo [id=1, name=a, category=c2, categories=null]], [Foo [id=2, name=a, category=c1, categories=null]]}
我想把它变成
[Foo [id=1, name=a, category=null, categories=[c1, c2]], Foo [id=2, name=a, category=null, categories=[c1]]]
i、 e.核对个人资料 category
进入一个列表 categories
.
这是实现我想要的当前代码。
public static void main(final String[] args) {
final Foo f1 = new Foo(1L, "a", "c1");
final Foo f2 = new Foo(1L, "a", "c2");
final Foo f3 = new Foo(2L, "a", "c1");
final List<Foo> li = List.of(f1, f2, f3);
li.forEach(e -> System.out.println(e));
final Map<Long, List<Foo>> collect = li.stream().collect(Collectors.groupingBy(Foo::getId));
System.out.println(collect);
final List<Foo> grouped = new ArrayList<>();
collect.forEach((k, v) -> {
System.out
.println("key=" + k + "val=" + v.stream().map(e1 -> e1.getCategory()).collect(Collectors.toList()));
final Foo foo = collect.get(k).get(0);
foo.setCategories(v.stream().map(e1 -> e1.getCategory()).collect(Collectors.toList()));
foo.setCategory(null);
grouped.add(foo);
});
System.out.println(grouped);
}
有没有任何方法可以单独使用streams和lambda而不必分成多个步骤来实现这一点?目标是使这段代码更加优雅、可读,并向读者传达意图。
这个问题在本质上类似于groupby和sum对象,比如在带有javalambdas的sql中?但是没有帮助我,因为这里做了聚合,而这里不是聚合。
1条答案
按热度按时间xdnvmnnf1#
可以通过实现
merge
函数,该函数将累积类别列表中的类别,然后使用reduce
流的操作:实施:
测试
输出
另一个选项是提供接受类别列表的foo构造函数:
然后Map条目可以很容易地重新Map到
Foo
包含类别列表的示例:在线演示