java基础Stream流中间操作中间操作

1. 状态

1.1. 有状态(stateful)

  1. sorted
  2. skip
  3. limit
  4. 任何触发状态变化的程序

1.2. 无状态(stateless)

  1. map
  2. reduce

2. 副作用

  1. 纯函数(pure function)
  2. 非纯函数

3. 筛选与切片

  1. filter(Predicate p) :接收 Lambda , 从流中排除某些元素
  2. distinct():筛选,通过流所生成元素的 hashCode() 和 equals() 去除重复元素 该对象必须实现hashcode和equals方法
  3. limit(long maxSize):截断流,使其元素不超过给定数量
  4. skip(long n):跳过元素,返回一个扔掉了前n 个元素的流。若流中元素不足 n 个,则返回一个空流。与 limit(n) 互补
  5. takewhile(Predicate<? super T> predicate)9 :产生一个流,它的元素是当前流中所有满足谓词条件的元素
  6. dropwhile(Predicate<? super T> predicate) 9:产生一个流,它的元素是当前流中排除不满足谓词条件的元素之外的所有元素
  7. concat(Stream<? extends T>a, Stream<? extends T>b):产生一个流,它的元素是a的元素后面跟着b的元素

4. 映射

4.1. map(Function f)

接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。

List<String> strList = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee");

Stream<String> stream = strList.stream().map(String::toUpperCase)

4.2. flatMap(Function f)

接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流

[["y","o","u","r"]["b","o","a","t"]]

."y","o","u","r","b","o","a","t",…..]

String d= "dd dvrfe niowanvewrod io0nerodv ionfe";
String[] s = d.split(" ");
List<String> d1 = Arrays.stream(s).map(s1 -> s1.split("d"))
.flatMap(s2 -> Arrays.stream(s2))
.collect(Collectors.toList());

4.3. mapToDouble(ToDoubleFunction f)

接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的DoubleStream

4.4. mapToInt(ToIntFunction f)

接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的IntStream

4.5. mapToLong(ToLongFunction f)

5. 排序

sorted()

sorted(Comparator com)

tream<CollectingIntoMaps.Person> personStream =
Stream.of(new CollectingIntoMaps.Person(1009, "Peter"), 
          new CollectingIntoMaps.Person(1002, "Paul"),
		  new CollectingIntoMaps.Person(1003, "Mary"));
List<CollectingIntoMaps.Person> collect = personStream.sorted
	(Comparator.comparing(CollectingIntoMaps.Person::getName)
 	.thenComparing(CollectingIntoMaps.Person::getId))
	.collect(Collectors.toList());

6. peek

不是一个最终操作,不会影响“哪些元素会流过”,所以十分适合在调试的时候,用来打印出流经管道的元素

Stream.of("one", "two", "three", "four")

.filter(e -> e.length() > 3)

.peek(e -> System.out.println("Filtered value: " + e))

.map(String::toUpperCase)

.peek(e -> System.out.println("Mapped value: " + e))

.collect(Collectors.toList());

  • 17
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值