通过合并对象或聚合对java8流进行分组

时间:2019-02-01 19:49:31

标签: java java-8 java-stream

我有以下情况,两个邻居物体和同一条街道但房屋不同。

我想知道如何使用流将我分组为一个邻居对象

总而言之,我有以下数据

drunk

我想将其合并以如下显示

Neighborhood: n11
streets: s11
houses: h1

Neighborhood: n11
streets: s11
houses: h2

代码如下

Neighborhood: n11
streets: s11
houses: h1,h2

2 个答案:

答案 0 :(得分:1)

好吧,您可以构建一个Map<String, Map<String, List<String>>>,其中键为Neighborhood::id,值为Map,键为Street::id,值{{1} }。从这里开始,将其重新构建为所需的东西……

House::id

答案 1 :(得分:0)

我不得不稍微修改一下您提供的代码:

import java.util.List;

public class Neighborhood {
    public String id;
    public List<Street> streets;

    public Neighborhood(String id, List<Street> streets) {
        this.id = id;
        this.streets = streets;
    }
}

class Street {

    public Street(String id, List<House> houses) {
        this.id = id;
        this.houses = houses;
    }

    public String id;
    public List<House> houses;
}

class House {
    public String id;

    public House(String id) {
        this.id = id;
    }
}

这是我的答案:

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Main {

    public static void main(String[] args) {
        House h1 = new House("h11");
        Street s1 = new Street("s11", Arrays.asList(h1));


        House h2 = new House("h12");
        Street s2 = new Street("s11", Arrays.asList(h2));

        Neighborhood n1 = new Neighborhood("n11", Arrays.asList(s1));
        Neighborhood n2 = new Neighborhood("n11", Arrays.asList(s2));

        Set<Street> collect = Stream.of(n1, n2).flatMap(neighborhood -> neighborhood.streets.stream())
                                          .collect(Collectors.toSet());

        System.out.println(collect);

        final Map<String, List<Street>> collect1 = collect.stream().collect(Collectors.groupingBy(street -> street.id));

        final List<Neighborhood> neighborhoods = new ArrayList<>();

        collect1.forEach((s, streets) -> {
            final List<House> collect2 = streets.stream().flatMap(street -> street.houses.stream())
                                                .collect(Collectors.toList());
            final Street street = new Street(s, collect2);
            neighborhoods.add(new Neighborhood(s, Arrays.asList(street)));
        });
    }
}