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); } }
