Java8之四:stream

有篇文章讲的很仔细:Java 8中stream相关用法

1.创建stream

public static void main(String[] args) {
	//1 Stream.of()
	Stream<Integer> stream = Stream.of(9,5,2,7);
	//2 Collection.stream()
	stream = Arrays.asList(9,5,2,7).stream();
}

2.中间操作:filter、map、limit、sorted、distinct

public static void main(String[] args) {
	//filter
	Stream<Integer> stream = Stream.of(9,5,2,7,2);
	stream.filter(n -> n > 5).forEach(System.out::println);//9 7
	//map
	stream = Stream.of(9,5,2,7,2);
	stream.map(n -> n + 1).forEach(System.out::println);   //10 6 3 8 3
	//limit
	stream = Stream.of(9,5,2,7,2);
	stream.limit(3).forEach(System.out::println);          //9 5 2
	//sorted
	stream = Stream.of(9,5,2,7,2);
	stream.sorted().forEach(System.out::println);          //2 2 5 7 9
	//distinct
	stream = Stream.of(9,5,2,7,2);
	stream.distinct().forEach(System.out::println);        //9 5 2 7
}

3.最终操作:foreach、count、collect

public static void main(String[] args) {
	//foreach
	Stream<Integer> stream = Stream.of(9,5,2,7,2);
	stream.filter(n -> n > 5).forEach(System.out::println);//9 7
	//count
	stream = Stream.of(9,5,2,7,2);
	stream.filter(n -> n > 5).count();                     //2
	//collect
	stream = Stream.of(9,5,2,7,2);
	stream.filter(n -> n > 5).collect(Collectors.toList());//List[9,7]
}

4.Map的putIfAbsent(非stream):putIfAbsent、computeIfAbsent、forEach

public static void main(String[] args) {
	Map<String,Integer> map = new HashMap<String,Integer>();
	map.putIfAbsent("a", 1);
	map.computeIfAbsent("b", k -> {
		int a = 1, b = 2;
		return a + b;
	});
	map.forEach((k,v) -> System.out.println(k+":"+v));
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值