首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用Java Stream API进行多级分组和求和

使用Java Stream API进行多级分组和求和
EN

Stack Overflow用户
提问于 2019-07-11 21:56:54
回答 1查看 138关注 0票数 4

我有一节课

代码语言:javascript
运行
复制
public class Person {

    private String name;
    private String country;
    private String city;
    private String pet;
    private int totalCountryToCityCount;
    private int petCount;

    public Person(String name, String country, String city, String pet, int total, int petCount) {
        this.name = name;
        this.country = country;
        this.city = city;
        this.pet = pet;
        this.totalCountryToCityCount = total;
        this.petCount = petCount;
    }

    public String getName() {
        return name;
    }

    public String getCountry() {
        return country;
    }

    public String getCity() {
        return city;
    }

    public String getPet() {
        return pet;
    }

    public int getPetCount() {
        return petCount;
    }

    public int getTotalCountryToCityCount() {
        return totalCountryToCityCount;

    }

}

在给定Person类列表的情况下,我根据类的不同属性进行了聚合。例如-

代码语言:javascript
运行
复制
Person person1 = new Person("John", "USA", "NYC", "Max", 1, 2);
        Person person2 = new Person("Steve", "UK", "London", "Lucy", 2, 8);
        Person person3 = new Person("Anna", "USA", "NYC", "Max", 4, 32);
        Person person4 = new Person("Mike", "USA", "Chicago", "Duke", 5, 1);
        Person person5 = new Person("Test", "INDIA", "HYD", "Tommy", 4, 32);
        Person person6 = new Person("Test1", "INDIA", "HYD", "Tommy", 4, 65);
        Person person7 = new Person("Tim", "USA", "Chicago", "Duke", 5, 111);
        Person person8 = new Person("Tim", "USA", "Chicago", "Puke", 5, 111);
        Person person9 = new Person("Test1", "INDIA", "DELHI", "Tommy", 4, 65);
List<Person> persons = Arrays
            .asList(person1, person2, person3, person4, person5, person6, person7, person8,
                person9);

现在我需要得到一个结果,我应该得到基于国家和城市组合的总"totalCountryToCityCount“,以及基于国家,城市和宠物组合的总"petCount”。我可以使用groupingBy和summingint分别获取它们

代码语言:javascript
运行
复制
private Map<String, Map<String, Integer>> getTotalCountForCountry(List<Person> persons) {
        return persons.stream().collect(groupingBy(Person::getCountry, getCityCount()));
    }

    public Collector<Person, ?, Map<String, Integer>> getCityCount() {
        return groupingBy(Person::getCity, summingInt(Person::getTotal));
    }

    public Map<String, Map<String, Map<String, Integer>>> threeLevelGrouping(List<Person> persons) {
       return  persons
            .stream().collect(
                groupingBy(Person::getCountry, groupByCityAndPetName()
                )
            );
    }

    private Collector<Person, ?, Map<String, Map<String, Integer>>> groupByCityAndPetName() {
        return groupingBy(Person::getCity, groupByPetName());
    }

    private Collector<Person, ?, Map<String, Integer>> groupByPetName() {
        return groupingBy(Person::getPet, summingInt(Person::getPetCount));
    }

它给出了结果

代码语言:javascript
运行
复制
{USA={Chicago={Puke=111, Duke=112}, NYC={Max=34}}, UK={London={Lucy=8}}, INDIA={DELHI={Tommy=65}, HYD={Tommy=97}}}
{USA={Chicago=15, NYC=5}, UK={London=2}, INDIA={DELHI=4, HYD=8}}

但我想要的实际结果是:

代码语言:javascript
运行
复制
{USA={Chicago={15,{Puke=111, Duke=112}}, NYC={5,{Max=34} }, UK={London={2, {Lucy=8}}, INDIA={DELHI={4, {Tommy=65}}, , HYD={8,{Tommy=97}}}}

有没有一种方法可以使用Java流API来实现同样的目的

我也试过使用代码-

代码语言:javascript
运行
复制
 personList.stream().collect(groupingBy(person -> person.getCountry(), collectingAndThen(reducing(
            (a, b) -> new Person(a.getName(), a.getCountry(), a.getCity(), a.getPet(),
                a.getTotal() + b.getTotal(), a.getPetCount() + b.getPetCount())),
            Optional::get)))
            .forEach((country, person) -> System.out.println(country + person));

但得到的结果是-

代码语言:javascript
运行
复制
USAPerson{name='John', country='USA', city='NYC'}
UKPerson{name='Steve', country='UK', city='London'}
INDIAPerson{name='Test', country='INDIA', city='HYD'}

令人惊讶的是计数被删除了

EN

回答 1

Stack Overflow用户

发布于 2019-07-12 17:24:03

您真正要找的是Collectors::teeing,但仅在java-12中可用:

代码语言:javascript
运行
复制
System.out.println(
        persons.stream()
               .collect(Collectors.groupingBy(
                   Person::getCountry,
                   Collectors.groupingBy(
                       Person::getCity,
                       Collectors.teeing(
                           Collectors.summingInt(Person::getTotalCountryToCityCount),
                           Collectors.groupingBy(
                               Person::getPet,
                               Collectors.summingInt(Person::getPetCount)
                           ),
                           SimpleEntry::new
                       )
                   ))));

java-8的一个后端,它是可用的here

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56990926

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档