Lambda使用笔记

1、累计列表对象中某个属性的和

  • 如果累加的是金额
// 解读 filter(状态为1).map(取出productAmount属性参数).filter(productAmount不为空).reduce(用BigDecimal的add方法累加productAmount).orElse(否则返回0);
BigDecimal totalAmount = productList.stream().filter(product -> "1".equals(product.getProductStatus())).map(Product::getProductAmount).filter(Objects::nonNull).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
System.out.println("totalAmount:" + totalAmount.toString());
  • 如果累加的是整型
int totalDay = productList.stream().filter(product -> "1".equals(product.getProductStatus())).mapToInt(Product::getProductTimeLimit).sum();
System.out.println("totalDay:" + totalDay);

2、用list里的对象的某个属性排序

  • 方法一
// 对调compareTo两边的属性控制倒序
List<Product> productListSorted = productList.stream().sorted((p, p1) -> (p.getProductSeq().compareTo(p1.getProductSeq()))).collect(Collectors.toList());
  • 方法二
// 可使用reversed()控制倒序
List<Product> productListSorted1 = productList.stream().sorted(Comparator.comparing(Product :: getProductSeq).reversed()).collect(Collectors.toList());
System.out.println("排序后:" + productListSorted.toString());

3、根据list里的对象的属性去除重复数据

注:lambda目前没有直接去重list里的对象的方法,需要自己写一个方法

// 去除重复数据
List<Product> productListDistinct = productList.stream().filter(distinctByKey(Product::getProductSeq)).collect(Collectors.toList());
System.out.println("去重后:" + productListDistinct.toString());

/**
 *@describe 自定义去重方法
 * @param keyExtractor
 * @return java.util.function.Predicate<T>
 */
public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
    Map<Object, Boolean> seen = new ConcurrentHashMap<>();
    return object -> seen.putIfAbsent(keyExtractor.apply(object), Boolean.TRUE) == null;
}

4、获取过滤后的list大小

  • 方法一
long listSize = productList.stream().filter(product -> "1".equals(product.getProductStatus())).count();
  • 方法二
int listSize1 = productList.stream().filter(product -> "1".equals(product.getProductStatus())).collect(Collectors.toList()).size();

5、List转Map对象

// 使用整个对象作为value
// productList.stream().collect(Collectors.toMap(对象的字段作为key, 整个对象作为value, (key1, key2) -> 两个相同的key,使用第一个key的值));
Map<String, Product> productMap = productList.stream().collect(Collectors.toMap(Product::getProductCode, Function.identity(), (key1, key2) -> key1));

// 使用指定字段作为value
Map<String, Product> productMap = productList.stream().collect(Collectors.toMap(Product::getProductCode, Product::getProductName, (key1, key2) -> key1));

6、List数据进行分组

// 按指定字段进行分组
Map<String, List<Product>> productMap = productList.stream().collect(Collectors.groupingBy(Product::getProductCode));

// 按指定字段进行分组,统计每组中数据量
Map<String, Long> productMap = productList.stream().collect(Collectors.groupingBy(Product::getProductCode, Collectors.counting()));

// 按指定字段进行分组,分组后将另一个字段转成List
Map<String, List<String>> productMap = productList.stream().collect(Collectors.groupingBy(Product::getProductCode, Collectors.mapping(Product::getProductName, Collectors.toList())));
posted @ 2021-01-11 20:16  土豆泥呀  阅读(139)  评论(0)    收藏  举报