stream与lambda表达式的使用

遍历集合含有索引

private Map findUserGroups(List results){
        Map map = Maps.newHashMap();
        Stream.iterate(0, i -> i + 1).limit(results.size())
                .filter(i -> results.get(i).contains("、"))
                .forEach(i ->
        map.put(String.valueOf(i),results.get(i))
  );
  return map;
}

常用操作

//rangeClosed包含末尾数据
long sum=LongStream.rangeClosed(1,10000000L).parallel().reduce(0,Long::sum);
System.out.println(sum);

//range不包含末尾节点
sum=LongStream.range(1,10000000L).parallel().reduce(0,Long::sum);
System.out.println(sum);

//求和reduce()
System.out.println(Stream.of(1,2,3,4).reduce((sum2,item)->{
      return sum2+item;
}).get());
System.out.println(Stream.of(1,2,3,4).reduce(Integer::sum).get());

//求最大值reduce()
System.out.println(Stream.of(1,2,3,4).reduce(100,(a,b)->Math.max(a, b)));
System.out.println(Stream.of(1,2,3,4).reduce(Integer::max).get());

//去重distinct()
System.out.println(Arrays.asList("a", "b", "c", "d", "a", "b", "c")
    .stream()
    .distinct()
    .collect(Collectors.toList())
);

//统计分组
System.out.println(Arrays.asList("apple", "apple", "banana",
    "apple", "orange", "banana", "papaya")
 .stream().collect(Collectors.groupingBy(Function.identity(),Collectors.counting()))
);

//统计排序
Map sortMap=new LinkedHashMap<>();
Arrays.asList("apple", "apple", "banana", "apple", "orange", "banana", "papaya")
    .stream()
.collect(Collectors.groupingBy(Function.identity(),Collectors.counting()))
.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue().reversed())
.forEachOrdered(e->sortMap.put(e.getKey(),e.getValue()));
System.out.println(sortMap);

运行结果:
运行结果

对含有BigDecimal字段的对象集合求和

BigDecimal result2 = userList.stream()
//将user对象的age取出来map为Bigdecimal
.map(User::getAge)
//使用reduce()聚合函数,实现累加器
.reduce(BigDecimal.ZERO,BigDecimal::add);

对int、double类型求和

int ageSum = userList.stream().collect(Collectors.summingInt(User::getAge));
System.out.println("年龄总和" + ageSum);

你可能感兴趣的:(stream与lambda表达式的使用)