在流中打开流

时间:2018-05-25 15:49:33

标签: java java-8 functional-programming java-stream

我有这段代码。我该如何改造它? 功能风格?事实上,我有List<X>。每个X包含List<V>。此列表中的每个V都有List<M>作为参数。我需要构建Map<X,Y>,其中Y是存储在对象X中聚合的所有V对象中的所有M个对象的数量。

HashMap<Country, Integer> modelsPerCountryMap = new HashMap<>();
int count;
for (Country country : CountryDataSingleton.getCountryDataCollection()) {
    count = 0;
    for (CarMaker cm : country.getListOfMakers()) {
        count += cm.getModels().size();
    }
    modelsPerCountryMap.put(country, count);
}

3 个答案:

答案 0 :(得分:5)

我将这些国家/地区流式传输,然后将它们收集到地图中,其中关键字是国家/地区,价值可以是制造商尺寸的总和:

Map<Country, Integer> modelsPerCountryMap =
     CountryDataSingleton.getCountryDataCollection()
                         .stream()
                         .collect(
                             Collectors.toMap(
                                 Function.identity(),
                                 c -> c.getListOfMakers()
                                       .stream()
                                       .mapToInt(cm -> cm.getModels().size())
                                       .sum()
                              )
                         );

答案 1 :(得分:0)

这样的事情:

公共类CountriesFunctionalTest {

private class CarMaker {

    private final String name;
    private final List<String> models;

    public CarMaker(String name, List<String> models) {
        this.name = name;
        this.models = models;
    }

    public String getName() {
        return name;
    }

    public List<String> getModels() {
        return models;
    }
}

private class Country {

    private final String name;
    private final List<CarMaker> makers;

    public Country(String name, List<CarMaker> makers) {
        this.name = name;
        this.makers = makers;
    }

    public String getName() {
        return name;
    }

    public List<CarMaker> getMakers() {
        return makers;
    }
}

@Test
public void test() throws DeliveryException {
    List<Country> countries = Arrays.asList(new Country[]{
            new Country("Country A", Arrays.asList(new CarMaker[]{ new CarMaker("Maker A", Arrays.asList(new String [] {"model a", "model a1", "model a2"})) })),
            new Country("Country B", Arrays.asList(new CarMaker[]{ new CarMaker("Maker B", Arrays.asList(new String [] {"model b", "model b1"})) })),
            new Country("Country C", Arrays.asList(new CarMaker[]{ new CarMaker("Maker C", Arrays.asList(new String [] {"model c", "model c1", "model c2", "model c3"})) }))
    });

    Map<Country, Integer> conuntriesModels = IntStream.range(0, countries.size()).mapToObj(i -> new AbstractMap.SimpleEntry<Country, Integer>(countries.get(i),
            IntStream.range(0, countries.get(i).getMakers().size())
                .map(ix -> countries.get(i).getMakers().get(ix).getModels().size()).sum()
                )
            ).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

    for (Country next : conuntriesModels.keySet()) {
        System.out.println(next.getName() + " models -> " + conuntriesModels.get(next));
    }
}

}

输出:

国家B型号 - &gt; 2

国家A型号 - &gt; 3

国家C型号 - &gt; 4

答案 2 :(得分:0)

如果您打算在java中使用,请考虑使用vavr.io。 Vavr为您提供了以方便一致方式应用功能范例所需的工具。在这种情况下,不可变数据结构。利用io.vavr.collection.Streamio.vavr.collection.HashMap,将您的数据收集到Map<Country, Integer>可能如下所示:

Stream.ofAll(CountryDataSingleton.getCountryDataCollection())
        .map(country -> Tuple.of(country, country.getListOfMakers().foldLeft(0, (acc, cm) -> acc + cm.getModels().size())))
        .foldLeft(HashMap.<Country, Integer>empty(), (acc, entry) -> acc.put(entry));