Stream流处理

Collectors.groupingBy() 汇总

对集合中元素进行分类汇总 如sql中的 GroupBy

public static <T, K> Collector<T, ?, Map<K, List<T>>> groupingBy(Function<? super T, ? extends K> classifier) { 
    return groupingBy(classifier, toList());                                                                     
}

Collector>,其最终返回的数据类型为:Map>

  • Java8之前 写法
Map<String, List<ShopCar>> shopBySellerNameMap = new HashMap<>();
   for(ShopCar c : shopCars ) {
       if(shopBySellerNameMap.containsKey( c.getSellerName() )) {
           shopBySellerNameMap.get(c.getSellerName()).add(c);
       } else {
           List<ShopCar> aList = new ArrayList<>();
           shopBySellerNameMap.put(c.getSellerName(), aList);
           aList.add(c);
      }
}

一级分类汇总 类似SQL group by sellerId

Map<String, List<ShopCar>> shopBySellerNameMap = shopCars.stream()
								               			 .collect(Collectors.groupingBy(ShopCar::getSellerName));
								               			 //.collect(Collectors.groupingBy( (ShopCar c) -> c.getSellerName() ))

二级分类汇总 类似SQL group by sellerId,buyerId

Map<String, Map<String, List<ShopCar>>>  result = shopCars.stream()
														  .collect(Collectors.groupingBy(ShopCar::getSellerName, Collectors.groupingBy(ShopCar::getBuyerName)));

Collectors.joining() 拼接

对集合元素进行拼接 如字符串集合拼接为一条String

public static Collector<CharSequence, ?, String> joining()
public static Collector<CharSequence, ?, String> joining(CharSequence delimiter)
public static Collector<CharSequence, ?, String> joining(CharSequence delimiter,CharSequence prefix, CharSequence suffix)

直接遍历拼接

List<String> stringList = Arrays.asList("A", "B", "C", "D", "E");
String result = stringList.stream().collect(Collectors.joining());
拼接结果:ABCDE

根据要求遍历拼接

List<String> stringList = Arrays.asList("A", "B", "C", "D", "E");
String result = stringList.stream().collect(Collectors.joining(",","_","—"));
拼接结果:_A,B,C,D,E

reduce() 归约

对集合中所有元素进行重复应用合并操作,最后产生一个单一的结果返回 如求和 相除 平均 拼接…

T reduce(T identity, BinaryOperator<T> accumulator)
  • java7之前的示例:
List<Integer> goodsNumber = Arrays.asList( 3, 5, 8, 4, 2, 13 );
int sum = 0;
for(Integer i : goodsNumber) {
	sum += i;//  sum = sum + i;
}
System.out.println("sum:" + sum);

三个参数含义:
第一个 0 初始值 如果goodsNumber为空则返回初始值0
第二个 参数a是上次累计的和,参数b是数据流的下一个元素
第三个 调用一个函数来组合归并操作的结果,当归并是并行执行或者当累加器的函数和累加器的实现类型不匹配时才会调用此函数。
(当顺序读流或者累加器的参数和它的实现的类型匹配时,我们不需要使用第三个参数组合器。)

List<Integer> goodsNumber = Arrays.asList( 3, 5, 8, 4, 2, 13 );
int sum = goodsNumber.stream().reduce(0, (a,b) -> a + b);
int sum = goodsNumber.stream().reduce(0, Integer::sum);
//并行流
int sum = goodsNumber.parallelStream().reduce(0, (a, b) -> a + b, Integer::sum);

为了避免基础数据类型的装箱/拆箱带来的性能损耗,引入了基础数据类型的函数式编程接口
例如IntStream、LongStream、DoubleStream

List<Dish> menu;
int calories = menu.stream()
                    .map(Dish::getCalories)
                    .reduce(0, Integer::sum);

IntStream本身提供了一些常用的聚合函数,例如sum。

List<Dish> menu;
int calories = menu.stream()
		           .mapToInt(Dish::getCalories)
		           .sum();

操作一个 String 类型的数组,把数组的字符串进行拼接

List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
String result = letters.stream()
				 	   .reduce("", (partialString, element) -> partialString + element);
String result = letters.stream().reduce("", String::concat);

filter() 过滤

对集合中元素进行判断 为真的保留 如从菜单中选出所有是素食的菜品:

Stream<T> filter(Predicate<? super T> predicate);
List<Dish> vegetarianDishs = menu.stream()
								 .filter( Dish::isVegetarian )  
                                 .collect(toList())

多条件过滤
and 和 or 是按照在表达式链中的位置,从左向右确定优先级的。因此, a.or(b).and( c) 可以看作 (a || b) && c 。

apples.filter((a -> "red".equals(a.getColor())).and(  a -> a.getWeight() > 150 ));
a -> "red".equals(a.getColor())(Apple a ) -> "red".equals(a.getColor())的简写。

distinct() 去重

对集合中元素进行去重 如sql中的distinct

numArr = [1,5,8,6,5,2,6]
Arrays.stream(numArr).filter(  a -> a % 2 == 0 ).distinict().forEach(System.out::println);

map() 操作

对集合中元素进行去重 如sql中的distinct

List<String> dishNames = menu.stream().map( (Dish d) ->d.getName()).collect(Collectors.toList());
List<String> dishNames = menu.stream().map( d -> d.getName() ).collect(Collectors.toList());
List<String> dishNames = menu.stream().map( d -> {
												  return d.getName();
										  })
										 .collect(Collectors.toList());
List<String> dishNames = menu.stream().map(Dish::getName).collect(Collectors.toList());

你可能感兴趣的:(java)