Java JDK8中lambda表达式的使用

1、List<实体类>根据某个字段返回Set<String>去重
 

  List<LcaTerm> lcaTerms = lcaTermMapper.selectByExample(lcaTermExample);
  Set<String> collect = lcaTerms.stream().map(LcaTerm::getBillNo).collect(Collectors.toSet());

​2、List<实体类>根据某个字段使用distinct去重

List<PaymentsGoodsInfo> paymentsGoodsInfoOrderIds = apQueryService.getPaymentsGoodsInfo(sellerId, sellerGoodsId,7L, ChronoUnit.DAYS);
List<String> userIds = paymentsGoodsInfoOrderIds.stream().map(PaymentsGoodsInfo::getAccountId).distinct().collect(Collectors.toList());

3、List<实体类>获取某个字段的最大值和最小值(建议使用第二种)

    
	List<PaymentsGoodsInfo> paymentsGoodsInfoOrderIds = apQueryService.getPaymentsGoodsInfo(sellerId, sellerGoodsId, 7L, ChronoUnit.DAYS);

    //最小值
	PaymentsGoodsInfo minPay = paymentsGoodsInfoOrderIds.stream().filter(pay -> !pay.getSellerId().equals(sellerId)).min(Comparator.comparing(PaymentsGoodsInfo::getPrice)).get();
	System.out.println("minPay:"+minPay.getPrice());


	
	//最大值
	PaymentsGoodsInfo maxPay = paymentsGoodsInfoOrderIds.stream().filter(pay -> !pay.getSellerId().equals(sellerId)).max(Comparator.comparing(PaymentsGoodsInfo::getPrice)).get();
	System.out.println("maxPay:"+maxPay.getPrice());

//-------------------第二种写法(带判空条件)-------------------------
    
    //如果paymentsGoodsInfoOrderIds == null 上面的写法get()方法就会抛出异常 建议使用这种写法
    Optional<PaymentsGoodsInfo> minPay = paymentsGoodsInfoOrderIds.stream().filter(pay -> !pay.getOrderId().equals(orderId)).min(Comparator.comparing(PaymentsGoodsInfo::getPrice));
        if (minPay != null && minPay.isPresent()) {
            System.out.println("minPay:"+minPay.get().getPrice());
        }


    Optional<PaymentsGoodsInfo> maxPay = paymentsGoodsInfoOrderIds.stream().filter(pay -> !pay.getOrderId().equals(orderId)).max(Comparator.comparing(PaymentsGoodsInfo::getPrice));
        if (maxPay != null && maxPay.isPresent()) {
            System.out.println("maxPay:"+maxPay.get().getPrice());
        }


4、List<String>快速获取最大值和最小值

    List<String> test1 = Arrays.asList("1", "7", "3");
	System.out.println(Collections.max(test1));
	System.out.println(Collections.min(test1));

5、BigDecimal求和 sum(restPayAmt)

	List<OrderInfo> successOrderInfoList = apQueryService.getSuccessOrderInfoList(orderIds, 24L, ChronoUnit.HOURS);
    BigDecimal restPayAmt = successOrderInfoList.stream().map(OrderInfo::getRestPayAmt).reduce(BigDecimal.ZERO, BigDecimal::add);
    System.out.println("restPayAmt:"+restPayAmt);

6、List<T>排序的使用

        //下面代码以自然序排序一个list
        list.stream().sorted();


        //自然序逆序元素,使用Comparator 提供的reverseOrder() 方法
        list.stream().sorted(Comparator.reverseOrder());


        //Age正序
        list.stream().sorted(Comparator.comparing(Student::getAge));


        //按Age来进行倒序
        list.stream().sorted(Comparator.comparing(Student::getAge).reversed());

7、List<实体类>分组(一对多)

        Map<String, List<Collocation>> listMap = list.stream().collect(Collectors.groupingBy(Collocation::getMasterName));
        System.out.println(JSON.toJSONString(listMap));

//        {
//            "李四":Array[1],
//            "喜洋洋":Array[1],
//            "张三":Array[1],
//            "王五":Array[1],
//            "哈哈":Array[1],
//            "爱仕达":Array[2],
//            "胡一菲":Array[3]
//        }

8、List<String> 分组

   public static void main(String[] args){
        //按输入类型,统计分组数量
        List<String> items = Arrays.asList("apple", "apple", "banana","apple", "orange", "banana", "papaya");
        Map<String, Long> result = items.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
        System.out.println(JSON.toJSONString(result));

//        {"papaya":1,"orange":1,"banana":2,"apple":3}


        //按输入类型,统计分组--排序
        Map<String, List<String>> result2 = items.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.toList()));
        System.out.println(JSON.toJSONString(result2));

//        {"papaya":["papaya"],"orange":["orange"],"banana":["banana","banana"],"apple":["apple","apple","apple"]}


        // result 排序
        Map<String, Long> finalMap = new LinkedHashMap<>();
        result.entrySet().stream().sorted(Map.Entry.<String, Long>comparingByValue().reversed())
                .forEachOrdered(e -> finalMap.put(e.getKey(), e.getValue()));
        System.out.println(JSON.toJSONString(finalMap));

//        {"apple":3,"banana":2,"papaya":1,"orange":1}

    }

 9、List<实体类>分组统计数量和排序

package com.lezu.springboot.dto;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.math.BigDecimal;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserDto {
    private String name;
    private Integer qty;
    private  BigDecimal money;

}




 public static void main(String[] args){
        List<UserDto> users = Arrays.asList(
                new UserDto("apple", 10, new BigDecimal(23)),
                new UserDto("apple", 20, new BigDecimal(32)),

                new UserDto("orange", 30, new BigDecimal(13)),
                new UserDto("orange", 20, new BigDecimal(33)),
                new UserDto("orange", 10, new BigDecimal(63)),

                new UserDto("peach", 20, new BigDecimal(26)),
                new UserDto("peach", 30, new BigDecimal(42)),
                new UserDto("peach", 40, new BigDecimal(24)),
                new UserDto("peach", 10, new BigDecimal(12))
        );

        // 按照name分组,并求出个数
        Map<String, Long> counting = users.stream().collect(Collectors.groupingBy(UserDto::getName, Collectors.counting()));
        System.out.println(JSON.toJSONString(counting));
        //{"orange":3,"apple":2,"peach":4}
        
        // 按照name分组,求和
        Map<String, Integer> sum = users.stream().collect(Collectors.groupingBy(UserDto::getName, Collectors.summingInt(UserDto::getQty)));
        System.out.println(JSON.toJSONString(sum));
        //{"orange":60,"apple":30,"peach":100}
        
        
        //统计name == orange的总和
        int basePoint3 = users.stream().filter(user -> user.getName().equals("orange")).mapToInt(UserDto::getQty).sum();
        System.out.println(JSON.toJSONString(basePoint3));
        //60
        

        
        // 按照name分组 转化List->Set,并且只取 getName作为新的list。
        Map<Integer, List<String>> result_list = users.stream()
                .collect(Collectors.groupingBy(UserDto::getQty, Collectors.mapping(UserDto::getName, Collectors.toList())));
        System.out.println(JSON.toJSONString(result_list));
        //{20:["apple","orange","peach"],40:["peach"],10:["apple","orange","peach"],30:["orange","peach"]}


        Map<String, Set<UserDto>> result_set = users.stream().collect(Collectors.groupingBy(UserDto::getName, Collectors.toSet()));
        System.out.println(JSON.toJSONString(result_set));
        //{"orange":[{"money":33,"name":"orange","qty":20},{"money":13,"name":"orange","qty":30},{"money":63,"name":"orange","qty":10}],"apple":[{"money":23,"name":"apple","qty":10},{"money":32,"name":"apple","qty":20}],"peach":[{"money":42,"name":"peach","qty":30},{"money":24,"name":"peach","qty":40},{"money":26,"name":"peach","qty":20},{"money":12,"name":"peach","qty":10}]}
        
        //按照name分组,可以简写,不需要,Collectors.toList()
        Map<String, List<UserDto>> groupByPriceMap = users.stream().collect(Collectors.groupingBy(UserDto::getName));
        System.out.println(JSON.toJSONString(groupByPriceMap));
        //{"orange":[{"money":13,"name":"orange","qty":30},{"money":33,"name":"orange","qty":20},{"money":63,"name":"orange","qty":10}],"apple":[{"money":23,"name":"apple","qty":10},{"money":32,"name":"apple","qty":20}],"peach":[{"money":26,"name":"peach","qty":20},{"money":42,"name":"peach","qty":30},{"money":24,"name":"peach","qty":40},{"money":12,"name":"peach","qty":10}]}
    }

posted @ 2021-10-30 15:35  难忘是想起  阅读(0)  评论(0)    收藏  举报  来源