首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java和SummingInt

Java和SummingInt
EN

Stack Overflow用户
提问于 2021-03-13 12:14:47
回答 4查看 343关注 0票数 1

我有一张福类的名单

代码语言:javascript
复制
class foo(){
  private String location;
  private int total;

  //constructor, getters, and setters
}

我想根据它们的位置对foo列表进行分组,并将它们加在一起,我如何使用Java流实现它?

代码语言:javascript
复制
expected output
[
  {
    "location" = "locationA",
    "total" = 123
  },
  {
    "location" = "locationB",
    "total" = 167
  }
]

我所取得的成就:

代码语言:javascript
复制
{locationA=123, locationB=167}

我的代码:

代码语言:javascript
复制
static Function<List<Case>, Object> totalPerYear = cases -> cases.stream()
                                                   .collect(Collectors.groupingBy((Case c)->c.getYear(), 
                                                   Collectors.summingInt((Case c)->c.getNumber())));
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2021-03-13 12:44:25

我假设您有一个具有公共名称和可变总价的对象的列表,并且希望添加与该命令名相对应的总计,并显示输出和相同的结构。以下是我如何尝试这样做的:

代码语言:javascript
复制
package com.example;

import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

class LocationData {
    String name;
    int total;

    public LocationData(String name, int total) {
        this.name = name;
        this.total = total;
    }

    public enum LocationNames {
        LocationA,
        LocationB,
        LocationC,
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getTotal() {
        return total;
    }

    public void setTotal(int total) {
        this.total = total;
    }
}

public class SampleStreamGroupBy {
    public static void main(String[] args) {
        List<LocationData> input = new ArrayList<>();
        input.add(new LocationData(LocationData.LocationNames.LocationA.name(), 1));
        input.add(new LocationData(LocationData.LocationNames.LocationA.name(), 2));
        input.add(new LocationData(LocationData.LocationNames.LocationA.name(), 3));
        input.add(new LocationData(LocationData.LocationNames.LocationB.name(), 4));
        input.add(new LocationData(LocationData.LocationNames.LocationB.name(), 100));
        input.add(new LocationData(LocationData.LocationNames.LocationC.name(), 5));

        Map<String, Integer> collect = input.stream()
                .collect(Collectors.groupingBy(LocationData::getName, Collectors.summingInt(LocationData::getTotal)));
        System.out.println(collect);

        List<LocationData> locationDataList = collect.entrySet().stream()
                .map(entry -> new LocationData(entry.getKey(), entry.getValue()))
                .collect(Collectors.toList());
        System.out.println(new Gson().toJson(locationDataList));
    }
}

应该打印类似于此的内容

代码语言:javascript
复制
{LocationC=5, LocationA=6, LocationB=104}
代码语言:javascript
复制
[{"name":"LocationC","total":5},{"name":"LocationA","total":6},{"name":"LocationB","total":104}]
票数 2
EN

Stack Overflow用户

发布于 2021-03-13 12:34:41

如果我正确地理解了您的需求,那么您希望为每个total找到属性location的值之和。如果是,你可以这样做:

代码语言:javascript
复制
Map<String, Integer> map = 
    list.stream()
    .collect(Collectors.groupingBy(Foo::getLocation, Collectors.summingInt(Foo::getTotal)));

演示:

代码语言:javascript
复制
public class Main {
    public static void main(String[] args) {
        List<Foo> list = List.of(new Foo("x", 10), new Foo("y", 5), new Foo("x", 15), new Foo("y", 10),
                new Foo("z", 10), new Foo("a", 10));

        Map<String, Integer> map = 
                list.stream()
                .collect(Collectors.groupingBy(Foo::getLocation, Collectors.summingInt(Foo::getTotal)));

        System.out.println(map);
    }
}

输出:

代码语言:javascript
复制
{a=10, x=25, y=15, z=10}
票数 2
EN

Stack Overflow用户

发布于 2021-03-13 12:51:00

我以为您希望将案例列表映射到foos列表:

代码语言:javascript
复制
class Main {

    private static List<Integer> costsList;

    public static void main(String args[]) throws Exception {
        List<Case> list = new ArrayList<>();
        list.add(new Case("2020", 4));
        list.add(new Case("2021", 2));
        list.add(new Case("2020", 2));
        list.add(new Case("2022", 3));
        List<Foo> foos = totalPerYear.apply(list);
        foos.forEach(System.out::println);

    }


    static Function<List<Case>, List<Foo>> totalPerYear = cases -> cases.stream()
            .collect(Collectors.groupingBy(Case::getYear, Collectors.summingInt(Case::getNumber)))
            .entrySet()
            .stream()
            .map(entry -> new Foo(entry.getKey(), entry.getValue()))
            .collect(Collectors.toList());


    static class Foo {
        private String year;
        private int total;

        public Foo(String year, int total) {
            this.year = year;
            this.total = total;
        }

        public String getYear() {
            return year;
        }

        public void setYear(String year) {
            this.year = year;
        }

        public int getTotal() {
            return total;
        }

        public void setTotal(int total) {
            this.total = total;
        }

        @Override
        public String toString() {
            return "Foo{" +
                    "year='" + year + '\'' +
                    ", total=" + total +
                    '}';
        }
    }

    static class Case {
        private String year;
        private int number;

        public Case(String year, int number) {
            this.year = year;
            this.number = number;
        }

        public String getYear() {
            return year;
        }

        public void setYear(String year) {
            this.year = year;
        }

        public int getNumber() {
            return number;
        }

        public void setNumber(int number) {
            this.number = number;
        }
    }
}

输出:

代码语言:javascript
复制
Foo{year='2022', total=3} 
Foo{year='2021', total=2} 
Foo{year='2020', total=6}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66613393

复制
相关文章

相似问题

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