List的分組,求和,過濾操作


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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM