流(Stream)部分操作和说明

部分基础操作

示例

System.out.println("empty:" + Stream.empty().collect(Collectors.toList()));
System.out.println("ofInteger:" + Stream.of(new Integer[]{1, 2, 3}).max(Comparable::compareTo).get());
System.out.print("ofString:");
Stream.of("2", "3", "2", "1", "1").distinct().sorted().forEach(System.out::print);
System.out.println();
System.out.println(Stream.generate(() -> "" + Math.random()).limit(2).collect(Collectors.joining()));
System.out.println(Stream.iterate(BigInteger.valueOf(0L), x -> x.add(BigInteger.valueOf(1L)))
        //注意,这里的skip和limit的顺序调换后的结果是不同的
        .skip(3).limit(10)
        .filter(x -> x.longValue() > 6 && x.longValue() < 14)
        .collect(Collectors.toList())
);
System.out.println(Arrays.stream(new String[]{"a", "b", "c"}).collect(Collectors.joining()));
System.out.println(Arrays.stream(new Integer[]{1, 2, 4, 6, 7}, 1, 4).count());

说明

  1. max、min、findFirst、findAny、reduce(第一种)返回的都是Optional类型,如果为空,则为空的Optional
  2. generate和iterate都返回无限流,前者通过Supplier每次返回一个新值;后者通过种子和累加器生成新值
  3. sorted未传Comparator的方法调用需要流中元素实现了内部比较器Comparable接口
  4. 关于toArray方法,再次说明,未传参数时,返回的是Object数组,数组转换比较麻烦,所以一般推荐使用传参的toArray

转换流元素

示例

//map
System.out.println(Stream.of(1, 2, 3, 4).map(x -> x * 2).collect(Collectors.toList()));
IntStream intStream = Stream.of("1", "2", "3").mapToInt(Integer::parseInt);
System.out.println(intStream.toArray()[2]);
System.out.println(Stream.of(new String[]{"1", "2"}, new String[]{"2", "4"}, new String[]{"3"}).flatMap(x -> Stream.of(x)).collect(Collectors.toSet()));

说明

  1. map、mapToInt、mapToLong、mapToDouble
    传入一个function,该function负责将流中元素转为对应的类型数据
  2. 对象流和基本类型流互转
    对象流转基本类型流:mapToInt、mapToLong、mapToDouble
    基本类型流转对象流:boxed
  3. map、flatMap(flatMapToInt、flatMapToLong、flatMapToDouble)
    map是将函数用于流中的每个元素,将返回值构成新的流;flatmap()是将函数应用于流中的每个元素,将返回的迭代器的所有内容构成新的流,这样就得到了一个由各列表中的元素组成的流,而不是一个列表组成的流。

collect

  1. toList、toSet、joining()、joining(delimiter)、joining(delimiter,prefix,suffix)
    常用的方法,转换为list、set、字符串
  2. toMap(fun1, fun2)、toConcurrentMap(fun1, fun2)、toMap(fun1, fun2, fun3)、toConcurrent Map(fun1,fun2,fun3)、toMap(fun1,fun2,fun3,fun4)同Concurrent Map(fun1,fun2,fun3,fun4)
    上面的fun1返回key,fun2返回value,fun3用来解决key冲突,fun4生成新的map用来存放结果
  3. toCollection(Supplier)
    supplier返回用来存放collection元素的空集合
  4. summarizingInt、summarizingLong、summarizingDouble
    返回对应类型的summaryStatistics对象,该对象有getCount等统计方法
  5. groupingBy(fun1)、groupingByConcurrent(fun1)、groupingBy(fun1,fun2)、groupingByConcurrent(fun1,fun2)、groupingBy(fun1,fun2,fun3)、groupingByConcurrent(fun1,fun2,fun3)
    fun用来生成Map,key为个元素执行fun的结果,value为对应的元素,fun2定义空的map用来保存结果,fun3用来对map.value中的值进行分组计算
  6. partitioningBy(fun1)、partitioningBy(fun1,fun3)
    类似groupingBy,只是fun1返回的结果是断言结果,key为bool值,效率会高点。fun3同样用来对分组后的值按组进行计算

reduce

格式:

  • Optional<T> reduce(BinaryOperator<T> accumulator);
  • T reduce(T identity, BinaryOperator<T> accumulator);
  • <U> U reduce(U identity,BiFunction<U, ? super T, U> accumulator,BinaryOperator<U> combiner);
    accumulator接受两个参数,分别对流中元素进行操作;identity是初始值,如果流为空则直接返回identity;combiner是组装方法,只在并行流操作时生效,用来对并行执行的结果进行组装。

示例

Stream<User> ofUserStream4Reduce = Stream.of(new User("name1"), new User("name2"), new User("name3"));
System.out.println(ofUserStream4Reduce.reduce(/**new User("name"), */(x, y) -> {
 y.setName(x.getName() + y.getName());
 return y;
}));
Function<User, User> f1 = (User user) -> {
 System.out.println("f1 applied");
 user.setName("f1" + user.getName() + "f1");
 return user;
};
Function<User, User> f2 = (User user) -> {
 System.out.println("f2 applied");
 user.setName("f2" + user.getName() + "f2");
 return user;
};
Function<User, User> f3 = (User user) -> {
 System.out.println("f3 applied");
 user.setName("f3" + user.getName() + "f3");
 return user;
};

Function<User, User> f4 = (User user) -> {
 System.out.println("f4 applied");
 user.setName("f4" + user.getName() + "f4");
 return user;
};

Stream<Function<User, User>> ofFunctionStream4Reduce = Stream.of(f2, f3);
Function<User, User> f5 = ofFunctionStream4Reduce.reduce((Function<User, User> fx1, Function<User, User> fx2) -> (User x) -> fx2.apply(fx1.apply(x))).get();
System.out.println(f5.apply(new User("name")));

//加上parallel后,执行的顺序被打乱
User u = Stream.of(f1,f2, f3, f4).parallel().reduce(new User("name"),
  (User user, Function<User, User> item) -> {
   item.apply(user);
   return user;
  }, (User user, User item) -> {
// System.out.println("user Name:" + user.getName());
// System.out.println("item Name:" + item.getName());
// return item.getName().length() > user.getName().length() ? item : user;
   return item;
  });
System.out.println(u);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值