zoukankan      html  css  js  c++  java
  • 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); } }
  • 相关阅读:
    Java基础12-继承(思想、覆盖、super,子类初始化)
    Java基础11-封装(思想、访问权限、this、构造方法)
    Java基础10-方法的重载与递归
    Java基础9-java的类、对象和方法
    Java基础8-浅谈java程序的运行机制与JVM运行
    Java基础7-数组
    Java基础6-控制语句
    Java基础5-运算符
    python socket编程基础
    python 之 异常处理
  • 原文地址:https://www.cnblogs.com/zgq7/p/9965147.html
Copyright © 2011-2022 走看看