Given the following example, I would like a stream function that sorts the list and also the nested list
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);
}
I have tried this:
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());
but this returns Bar, whilst I want a list of Foo
Fooobjects (that wouldn't be terribly functional...) or create newFooobjects with a sorted list ofBarobjects?Foo.barsin-place or create new instances ofFoo. In the former case, just callList.sorton these lists. In the latter case, you have to construct newFooinstances in yourmapoperation.