Java 8 Streams - 按层次排序嵌套列表 [英] Java 8 Streams - Sort nested lists hierarchically

查看:975
本文介绍了Java 8 Streams - 按层次排序嵌套列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于以下示例,我想要一个对列表进行排序的流函数以及嵌套列表

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);

}

我试过这个:

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列表

but this returns Bar, whilst I want a list of Foo

推荐答案

List<Foo> foosSort = foos.stream()
                     .sorted((o1, o2) -> (o1.sort - o2.sort))
                     .map(f -> {
                          List<Bar> bars = f.bars.stream()
                            .sorted((o1, o2) -> (o1.sort- o2.sort))
                            .collect(Collectors.toList());
                          f.bars = bars;
                          return f;
                     })
                     .collect(Collectors.toList());

这篇关于Java 8 Streams - 按层次排序嵌套列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆