当前位置:网站首页>List uses stream flow to add according to the number of certain attributes of the element

List uses stream flow to add according to the number of certain attributes of the element

2022-07-05 15:58:00 Ant HJK

Need to be on a List Remove duplicate unique value attributes of objects in , Attribute summation , The object is assumed to be BillsNums, Yes id、nums、sums Three attributes , among id Represents a unique value , need nums And sums In sum , And finally keep one .
For example, :(“s1”, 1, 1),(“s1”,2,3),(“s2”,4,4), Sum and remove the weight , Namely (“s1”, 3, 4),(“s2”,4,4)

Objects and properties
class BillsNums {
    private String id;
    private int nums;
    private int sums;
    
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public int getNums() {
        return nums;
    }
    public void setNums(int nums) {
        this.nums = nums;
    }
    public int getSums() {
        return sums;
    }
    public void setSums(int sums) {
        this.sums = sums;
    }
}

data
public static void main(String[] args) {
 
    List<BillsNums> billsNumsList = new ArrayList<>();
    BillsNums billsNums = new BillsNums();
    billsNums.setId("1001");
    billsNums.setNums(2);
    billsNums.setSums(100);
    billsNumsList.add(billsNums);
 
    BillsNums billsNums2 = new BillsNums();
    billsNums2.setId("1001");
    billsNums2.setNums(3);
    billsNums2.setSums(100);
    billsNumsList.add(billsNums2);
 
    List<BillsNums> result = merge(billsNumsList);
    System.out.println("result:" + JSON.toJSONString(result, true));
}

/**
 * take id A merger nums, sums The set after adding a round and using Java8 Process the stream
 */
public static List<BillsNums> merge(List<BillsNums> list) {
        List<BillsNums> result = list.stream()
        // Express id by key, Then if there is a repetition , So from BillsNums object o1 And o2 Filter out one , Choose here o1,
        // And put id repeat , Need to put nums and sums And o1 To merge o2, Assign a value to o1, Finally back to o1
        .collect(Collectors.toMap(BillsNums::getId, a -> a, (o1,o2)-> {
            o1.setNums(o1.getNums() + o2.getNums());
            o1.setSums(o1.getSums() + o2.getSums());
            return o1;
        })).values().stream().collect(Collectors.toList());
        return result ;
}

原网站

版权声明
本文为[Ant HJK]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207051526233658.html