Java8 stream一些用法

1、map、reduce的用法

		List<TestsObject> list = new ArrayList<TestsObject>();
		TestsObject object1 = new TestsObject(1,"tom","beijing",12,20.8);
		list.add(object1);
		TestsObject object2 = new TestsObject(2,"jack","shanghai",15,21.8);
		list.add(object2);
		TestsObject object3 = new TestsObject(3,"lose","guangzhou",18,33.8);
		list.add(object3);
		TestsObject object4 = new TestsObject(4,"alise","beijing",23,13.8);
		list.add(object4);
		TestsObject object5 = new TestsObject(5,"bob","shanghai",10,34.8);
		list.add(object5);
		//1、求和 map-reduce
		Optional<Double> optional = list.stream().map(TestsObject::getScore).reduce((a,b) -> a + b);
		if (optional.isPresent()) {
			Double scoreDouble = optional.get();
			System.out.println(scoreDouble);
		}
		//2、求和
		DoubleStream mapToDouble = list.stream().mapToDouble(TestsObject::getScore);
		double sum = mapToDouble.sum();
		System.out.println("sum="+sum);
		
		//1、求平均值
		double avg = list.stream().mapToDouble(TestsObject::getScore).average().getAsDouble();
		System.out.println("avg="+avg);
		
		//map用法
		List<Integer> list2 = list.stream().map(TestsObject::getAge).map(t -> t - 1).collect(Collectors.toList());
		//map用法
		list = list.stream().map(t -> {
			t.setAge(11);
			return t;
		}).collect(Collectors.toList());

2、flatMap的用法
案例一:

		List<String> words = Arrays.asList("hello c++","hello java","hello python");
		//把集合用的元素按空格切割,成一个数组
		Stream<String[]> stream = words.stream().map(word -> word.split(" "));
		//利用flatMap把数组转换为集合类型,并对元素去重
		List<String> resultList = stream.flatMap(Arrays::stream).distinct().collect(Collectors.toList());
		for (String string : resultList) {
			System.out.println(string);
		}

案例二:

		List<String> hobby1 = Arrays.asList("java","c","音乐");
		User user1 = new User(1, "zhangsan", hobby1);
		List<String> hobby2 = Arrays.asList("c++","c","游戏");
		User user2 = new User(2, "lisi", hobby2);
		//集合元素中还有集合
		List<User> list = new ArrayList<User>(2);
		list.add(user1);
		list.add(user2);
		//利用flatMap取出集合中的集合的元素并去重
		Stream<String> stream = list.stream().map(User::getHobby).flatMap(Collection::stream);
		List<String> list2 = list.stream().map(User::getHobby).flatMap(Collection::stream).distinct().collect(Collectors.toList());
		list2.forEach(t -> {
			System.out.println(t);
		});

虽然写的很粗糙,但是很常用!浏览到此篇文章的小伙伴,希望会对你们有帮助!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值