首页 > 编程语言 >Java8 - sum求和,将 List 集合转为 Map,key去重(groupingBy),sorted排序

Java8 - sum求和,将 List 集合转为 Map,key去重(groupingBy),sorted排序

时间:2023-04-10 23:22:53浏览次数:34  
标签:Map stream groupingBy goodsPriceDTOS sum GoodsPriceDTO amount new goodName

Java8 - sum求和,将 List 集合转为 Map,key去重(groupingBy),sorted排序

package com.example.core.mydemo.java8;

public class GoodsPriceDTO {
    private Integer id;
    private String goodName;
    private Integer amount;

    //重写toString方法,System可以打印输出对象
    @Override
    public String toString() {
        return "GoodsPriceDTO{" +
                "id=" + id +
                ", goodName='" + goodName + '\'' +
                ", amount=" + amount +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getGoodName() {
        return goodName;
    }

    public void setGoodName(String goodName) {
        this.goodName = goodName;
    }

    public Integer getAmount() {
        return amount;
    }

    public void setAmount(Integer amount) {
        this.amount = amount;
    }
}
package com.example.core.mydemo.java8;

import java.util.*;
import java.util.stream.Collectors;

public class GoodsTotalTest {
    public static void main(String[] args) {
        List<GoodsPriceDTO> goodsPriceDTOS = new ArrayList<GoodsPriceDTO>();
        GoodsPriceDTO dto = new GoodsPriceDTO();
        dto.setId(1);
        dto.setGoodName("Apple1");
        dto.setAmount(27);
        goodsPriceDTOS.add(dto);

        GoodsPriceDTO dto2 = new GoodsPriceDTO();
        dto2.setId(2);
        dto2.setGoodName("Orange");
        dto2.setAmount(28);
        goodsPriceDTOS.add(dto2);

        GoodsPriceDTO dto3 = new GoodsPriceDTO();
        dto3.setId(3);
        dto3.setGoodName("Banana");
        dto3.setAmount(29);
        goodsPriceDTOS.add(dto3);

        GoodsPriceDTO dto4 = new GoodsPriceDTO();
        dto4.setId(4);
        dto4.setGoodName("Apple4");
        dto4.setAmount(23);
        goodsPriceDTOS.add(dto4);

        //重复键key
        GoodsPriceDTO dto5 = new GoodsPriceDTO();
        dto5.setId(4);
        dto5.setGoodName("Apple5");
        dto5.setAmount(100);
        goodsPriceDTOS.add(dto5);


        int amt = Optional.ofNullable(goodsPriceDTOS)
                .orElseGet(ArrayList::new)
                .stream()
                .filter(x -> x != null && ("Apple".equals(x.getGoodName()))).mapToInt(GoodsPriceDTO::getAmount).sum();
        System.out.println("amt=" + amt);

        //Java8 - 将 List 集合转为 Map
        //List转map
        Map<Integer,GoodsPriceDTO> map = Optional.ofNullable(goodsPriceDTOS)
                .orElseGet(ArrayList::new)
                .stream().collect(Collectors.toMap(GoodsPriceDTO::getId,GoodsPriceDTO->GoodsPriceDTO,(oldValue,newValue)->oldValue));
        System.out.println("map=" + map);

        //List转map -2
        Map<Integer,String> map2 = Optional.ofNullable(goodsPriceDTOS)
                .orElseGet(ArrayList::new)
                .stream().collect(Collectors.toMap(GoodsPriceDTO::getId,GoodsPriceDTO::getGoodName,(oldValue,newValue)->oldValue));
        System.out.println("map2=" + map2);

        //如果出现相同的key,那么会抛出重复key的异常
        //Duplicate key com.example.core.mydemo.java8.GoodsPriceDTO@20ad9418
        //输出: map2={1=Apple1, 2=Orange, 3=Banana, 4=Apple4}

        //刚才上面出现重复的ID,是根据值进行覆盖,在某些情况下需要映射成列表。即:List -> Map<Integer, List>的情况。
        Map<Integer,List<GoodsPriceDTO>> map3 = Optional.ofNullable(goodsPriceDTOS)
                .orElseGet(ArrayList::new)
                .stream().collect(Collectors.groupingBy(GoodsPriceDTO::getId));
        System.out.println("map3=" + map3);
        //map3={1=[GoodsPriceDTO{id=1, goodName='Apple1', amount=27}], 2=[GoodsPriceDTO{id=2, goodName='Orange', amount=28}], 3=[GoodsPriceDTO{id=3, goodName='Banana', amount=29}], 4=[GoodsPriceDTO{id=4, goodName='Apple4', amount=23}, GoodsPriceDTO{id=4, goodName='Apple5', amount=100}]}

        //Comparator 升序
        List<GoodsPriceDTO> newSortedList = Optional.ofNullable(goodsPriceDTOS)
                .orElseGet(ArrayList::new)
                .stream().sorted(Comparator.comparing(GoodsPriceDTO::getAmount)).collect(Collectors.toList());

        //按价格排序:
        newSortedList.stream().forEach(x -> {
            System.out.println("x=" + x);
        });

        //Comparator 降序
        List<GoodsPriceDTO> newSortedList1 = Optional.ofNullable(goodsPriceDTOS)
                .orElseGet(ArrayList::new)
                .stream().sorted(new Comparator<GoodsPriceDTO>() {
                    @Override
                    public int compare(GoodsPriceDTO o1, GoodsPriceDTO o2) {
                        return o2.getAmount().compareTo(o1.getAmount());
                    }
                }).collect(Collectors.toList());

        //按价格排序:
        newSortedList1.stream().forEach(x -> {
            System.out.println("x1=" + x);
        });



        //升序
        List<GoodsPriceDTO> newSortedList2 = Optional.ofNullable(goodsPriceDTOS)
                .orElseGet(ArrayList::new)
                .stream().sorted((a,b) ->(a.getAmount() - b.getAmount())).collect(Collectors.toList());

        //按价格排序:
        newSortedList2.stream().forEach(x -> {
            System.out.println("x2=" + x);
        });

        //降序
        List<GoodsPriceDTO> newSortedList3 = Optional.ofNullable(goodsPriceDTOS)
                .orElseGet(ArrayList::new)
                .stream().sorted((a,b) ->(b.getAmount() - a.getAmount())).collect(Collectors.toList());

        //按价格排序:
        newSortedList3.stream().forEach(x -> {
            System.out.println("x3=" + x);
        });

    }
}

 

标签:Map,stream,groupingBy,goodsPriceDTOS,sum,GoodsPriceDTO,amount,new,goodName
From: https://www.cnblogs.com/oktokeep/p/17304708.html

相关文章

  • Sum of Consecutive Prime Numbers UVA - 121
     #include<iostream>#include<cstring>#include<cmath>#include<algorithm>usingnamespacestd;constintM=1e4+33;intb[M],c[M],tot;ints[M];voidinit(inttop){memset(b,1,sizeofb);b[1]=0;inti,j;......
  • Sum of Different Primes UVA - 1213
     选择K个质数,使它们的和等于N。问有多少种方案?例如,n=24,k=2时有3种方案:5+19=7+17=11+13=24 #include<iostream>#include<cstring>#include<cmath>#include<algorithm>usingnamespacestd;constintM=1e6+33;intb[M],c[M],tot;intn,m,f[2000][20];......
  • map集合的3中遍历方式
    键找值://创建map的对象Map<String,String>map=newHashMap<>();//添加元素map.put("11","11");//通过找值,获取所有的键放到一个单列集合中去Set<String>key=map.keySet();//遍历键key.forEach(newConsume......
  • 禁用 DevTools 源映射功能, 隐藏 "DevTools failed to load SourceMap" 报错
    警告DevToolsfailedtoloadsourcemap:Couldnotloadcontentforchrome-extension://cofdbpoegempjloogbagkncekinflcnj/build/content.js.map:系统错误:net::ERR_BLOCKED_BY_CLIENT这个问题可能是因为浏览器的版本不同,所以设置的位置也会略有不同。以下是几个常见浏......
  • MIT 6.5840 2023 Spring(6.824)LAB1:MapReduce
    MIT6.58402023Spring(6.824)LAB1:MapReduce前言本次lab主要是完成一个基于RPC远程调用的单机单文件系统的简单MapReduce框架,并完成单词计数任务。基于golang实现,单Master,多Worker。实现worker的奔溃恢复(FaultTorrance),通过超时重新执行实现。主要的任务有,RPC调用参数及返回参数......
  • List<Map<String, Object>> 排序
    一、代码publicclassTest{publicstaticvoidmain(String[]args){Map<String,Object>map=newHashMap<String,Object>();map.put("name","ZK");map.put("age",13);Map<Str......
  • 分布式计算技术(上):经典计算框架MapReduce、Spark 解析
    当一个计算任务过于复杂不能被一台服务器独立完成的时候,我们就需要分布式计算。分布式计算技术将一个大型任务切分为多个更小的任务,用多台计算机通过网络组装起来后,将每个小任务交给一些服务器来独立完成,最终完成这个复杂的计算任务。本篇我们介绍两个经典的计算框架MapReduce和Sp......
  • 【Java 并发】【十】【JUC数据结构】【七】ConcurrentHashMap前置篇HashMap原理
    1 前言前几节我们分析了一些并发安全的数据结构,分别是CopyOnWrite系列的CopyOnWriteArrayList、BlockingQueue阻塞队列系列的LinkedBlockingQueue、ArrayBlockingQueue、DelayQueue。接下来我们要讲解一个很重要的并发安全的数据结构,ConcurrentHashMap。在Java的数据结构里面平......
  • 【spring学习笔记】(二)Spring MVC注解配置 参数转换注解@RequestMapping@RequestParam
    @TOC介绍在SpringMVC项目中,<\context:component-scan>配置标签还会开启@Request-Mapping、@GetMapping等映射注解功能(也就是会注册RequestMappingHandler-Mapping和RequestMappingHandlerAdapter等请求映射和处理等组件),但是<context:component-scan>不支持数据转换或验证等注解功......
  • Do you know the bitwise sum sample demonstrated in "Neural Networks and Deep Lea
    Doyouknowthebitwisesumsampledemonstratedin"NeuralNetworksandDeepLearning"byautor MichaelNielsen?Yes,Iamfamiliarwiththebitwisesumexampledemonstratedin"NeuralNetworksandDeepLearning"byMichaelNielsen......