lambda-stream(filter, limit, skip, distinct, map, flatMap, sorted)

streams的三个步骤

  1. 创建stream
  2. 中间操作
  3. 终止操作(终端操作)

筛选与切片

  1. filter—接受Lambda,从流中排出某些元素
List<String> list = Arrays.asList("bbb", "aaa", "ddd", "aaa", "ccc", "ddd", "eee");
list.stream().filter(e -> "aaa".equals(e)).forEach(e -> System.out.print(e + " "));
outPut : aaa aaa 
  1. limit—截断流,使其元素不能超过给定数量
List<String> list = Arrays.asList("bbb", "aaa", "ddd", "aaa", "ccc", "ddd", "eee");
list.stream().filter(e -> "aaa".equals(e)).limit(1).forEach(e -> System.out.print(e + " "));
outPut : aaa
  1. skip(n)—跳过元素,返回一个扔掉了前n个元素的流,若流中元素不足n个,则返回一个空流,与limit(n)互补
List<String> list = Arrays.asList("bbb", "aaa", "ddd", "aaa", "ccc", "ddd", "eee");
list.stream().skip(2).forEach(e -> System.out.print(e + " "));
outPut : ddd aaa ccc ddd eee 
  1. distinct—筛选,通过流所生成元素的hashCode()和equals()去除重复元素
List<String> list = Arrays.asList("bbb", "aaa", "ddd", "aaa", "ccc", "ddd", "eee");
list.stream().distinct().forEach(e -> System.out.print(e + " "));
outPut : bbb aaa ddd ccc eee 

映射

  1. map–接受映射Lambda,将元素转换成其他形式或提取信息。接收另一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。
public void mapTest() {
	List<String> list = Arrays.asList("bbb", "aaa", "ddd", "aaa", "ccc", "ddd", "eee");
	list.stream().map(e -> e.toUpperCase()).forEach(e -> System.out.print(e + " "));
}
outOut : BBB AAA DDD AAA CCC DDD EEE 
  1. flatMap–接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有的流连接成一个流
@Test
public void mapTest() {
	List<String> list = Arrays.asList("bbb", "aaa", "ddd", "aaa", "ccc", "ddd", "eee");
	
	Stream<Stream<Character>> stream = list.stream().limit(2).map(e -> filterCharacter(e));
	System.out.print("map:");
	//返回的stream里的每个值都是流
	stream.forEach(sm -> {
		sm.forEach(e -> {System.out.print(e + " ");});
	});
	System.out.println();
	System.out.print("flarMap:");
	//返回的流直接连接成一个流
	Stream<Character> stream2 = list.stream().limit(2).flatMap(e -> filterCharacter(e));
	stream2.forEach(e -> System.out.print(e + " "));
}

public static Stream<Character> filterCharacter(String str) {
	List<Character> list = new ArrayList<>();
	for (Character ch : str.toCharArray()) {
		list.add(ch);
	}
	return list.stream();
}
outPut : map:b b b a a a 
		 flarMap:b b b a a a 

排序

  1. sorted()–自然排序
List<Integer> list = Arrays.asList(5, 3, 4, 1, 2);
list.stream().sorted().forEach(e -> System.out.print(e + " "));
outPut : 1 2 3 4 5 
  1. sorted(comparator com)–定制排序
List<Integer> list = Arrays.asList(5, 3, 4, 1, 2);
list.stream().sorted((x, y) -> y.compareTo(x)).forEach(e -> System.out.print(e + " "));
outPut : 5 4 3 2 1
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值