List的分组,求和,过滤操作

时间:2022-11-18 06:04:05
package ---;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors; /**
* Created by zhugenqi on 2018/9/18 0018.
*/
class ListToMap {
private static List<Apple> appleList = new ArrayList<>();//存放apple对象集合; public static void main(String[] args) throws Exception {
Apple apple1 = new Apple(1, "苹果1", new BigDecimal("3.25"), 10);
Apple apple12 = new Apple(1, "苹果2", new BigDecimal("1.35"), 20);
Apple apple13 = new Apple(2, "苹果13", new BigDecimal("1.35"), 20);
Apple apple2 = new Apple(2, "香蕉", new BigDecimal("2.89"), 30);
Apple apple3 = new Apple(3, "荔枝", new BigDecimal("9.99"), 40);
appleList.add(apple1);
appleList.add(apple12);
appleList.add(apple13);
appleList.add(apple2);
appleList.add(apple3);
toMap(appleList);
} private static void toMap(List<Apple> appleList) throws Exception {
//转化为map,并且对 key 去重
Map<Integer, Apple> AppleMap = appleList.stream()
.collect(Collectors
.toMap(Apple::getId, apple -> apple, (k1, k2) -> k1)
);
//根据分组
Map<Integer, List<Apple>> AppleMap02 = appleList.stream().collect(Collectors.groupingBy(Apple::getId)); //筛选出name为香蕉的code
List<Apple> AppleMap03 = appleList.stream().filter(apple -> apple.getName().equals("香蕉")).collect(Collectors.toList()); //分组求和
BigDecimal TotalMoney = appleList.stream().map(Apple::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal sum = appleList.stream().filter(apple -> apple.getName().equals("香蕉")).map(Apple::getMoney).reduce(BigDecimal.ZERO,BigDecimal::add); //算出name的种类数量,并转为set
Set<String> names = appleList.stream().map(Apple::getName).collect(Collectors.toSet());
System.out.println("主键去从");
System.out.println(AppleMap);
System.out.println("分组");
for (Map.Entry entry : AppleMap02.entrySet()) {
System.out.print(entry.getKey() + " ");
List list = (List) entry.getValue();
for (Object object : list) {
if (list.indexOf(object) > 0) {
System.out.print(" ");
}
System.out.println(object);
}
}
System.out.println("过滤");
System.out.println(AppleMap03); System.out.println("求和");
System.out.println("总价格 :" + TotalMoney); System.out.println("分组求和");
System.out.println("总数量 : " + sum); System.out.println("输出种类");
System.out.println("种类 : "+names);
}
}