给出以下示例,我想要一个对列表和嵌套列表进行排序的流函数
class Foo {
public int sort;
public List<Bar> bars;
public Foo(int sort) {
this.sort = sort;
}
}
class Bar {
public int sort;
public Bar(int sort) {
this.sort = sort;
}
}
@Test
public void testSortering() {
Foo foo = new Foo(1);
Foo foo2 = new Foo(2);
Bar bar = new Bar(1);
Bar bar2 = new Bar(2);
foo.bars = Arrays.asList(bar2, bar);
foo2.bars = Arrays.asList(bar2, bar);
List<Foo> foos = Arrays.asList(foo2, foo);
//I would like to iterate foos and return a new foos sorted, and with bars sorted, so that this goes green
assertEquals(1, foos.get(0).sort);
assertEquals(1, foos.get(0).bars.get(0).sort);
assertEquals(2, foos.get(0).bars.get(1).sort);
assertEquals(2, foos.get(1).sort);
assertEquals(1, foos.get(1).bars.get(0).sort);
assertEquals(2, foos.get(1).bars.get(1).sort);
}
我已经尝试过这个:
List<List<Bar>> foosSorted = foos.stream()
.sorted((o1, o2) -> Integer.compare(o1.sort, o2.sort))
.map(f -> f.bars.stream().sorted((o1, o2) -> Integer.compare(o1.sort, o2.sort)).collect(Collectors.toList()))
.collect(Collectors.toList());
但这会返回 Bar,而我想要 Foo 的列表
下面将排序foos
和bars
对于每个foo
,但自从peek
操作正在变异f
,如果涉及并行性,这将会产生意想不到的行为。
List<Foo> foosSorted = foos.stream()
.sorted(Comparator.comparingInt(o -> o.sort))
.peek(f -> {
f.bars = f.bars.stream().sorted(Comparator.comparingInt(o -> o.sort)).collect(Collectors.toList());
})
.collect(Collectors.toList());
我建议你添加一个构造函数Foo
taking sort
and bars
并使用map
代替peek
。这样,我们就不会改变任何Foo
对象,因此可以毫无问题地并行运行。
List<Foo> foosSorted = foos.stream()
.sorted(Comparator.comparingInt(o -> o.sort))
.map(f -> {
return new Foo(f.sort, f.bars.stream().sorted(Comparator.comparingInt(o -> o.sort)).collect(Collectors.toList()));
})
.collect(Collectors.toList());
with:
class Foo {
public int sort;
public List<Bar> bars;
public Foo(int sort) {
this.sort = sort;
}
public Foo(int sort, List<Bar> bars) {
this.sort = sort;
this.bars = new ArrayList<>(bars);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)