Stream API小结

Stream API

1、为什么用

提供了高效且易于使用的处理数据方式。

2、特点

1.不会自己存储元素

2、不会改变源对象

3、延迟执行,等到需要结果时才执行。

3、分类

1、中间操作/无状态:

unordered()/filter()/map()/mapToInt()/mapToLong()/mapToDouble()

/flatMap()/flatMapToInt()/flatMapToLong()/flatMapToDouble()/peek()

2、中间操作(有状态)

distinct()/sorted()/limit()/skip()

3、结束操作(非短路)

:forEaach()/foreachOrdered()/toArray()/reduce()/collect()/max()/min()/count()

4、结束操作(短路)

:anyMatch()/allMatch()/noneMatch()/findFirst()/findAny()

短路操作:遇到某些符合条件的元素就可以得到最终结果。
非短路:必须处理所有元素才能得到最终结果。

4、具体方法

1、流的常用创建方法

1.1使用Collection下的stream()和parallelStream()方法
List<String> list = new ArrayList<>();
Stream<String> stream = list.stream();
Stream<String> parallelStream = list.parallelStream();//获取一个并行流
1.2 Array下的stream()方法
		Integer[] nums = new Integer[10];
		Stream<Integer> stream1 = Arrays.stream(nums);

		



		

		//流的中间操作
		
1.3 使用Stream()中的静态方法
		Stream<Integer> stream2 = Stream.of(1, 2, 3, 4, 5, 6);

		Stream<Integer> stream3 = Stream.iterate(0, (x) -> x + 2).limit(6);
		stream3.forEach(System.out::println);

		Stream<Double> stream4 = Stream.generate(Math::random).limit(2);
		stream4.forEach(System.out::println);
1.4使用BuffererReader.lines()
		BufferedReader reader = new BufferedReader(new FileReader("C:\\test"));
		Stream<String> lineStream = reader.lines();
		lineStream.forEach(System.out::println);
1.5 使用Pattern.splitAsStream()方法,将字符串分隔成流
		Pattern pattern = Pattern.compile(",");
		Stream<String> stringStream = pattern.splitAsStream("a,s,f,g");
		stringStream.forEach(System.out::println);

2、流的中间操作

2.1筛选与切片
//filter:过滤某些元素
		Stream<Integer> stream5 = Stream.of(3, 4, 2, 5, 4, 4, 2);

		Stream<Integer> newStream = stream5.filter(s -> s > 5)
				.distinct()
//				.skip(2)
				.limit(2);
		newStream.forEach(System.out::println);
2.2映射

map;接受一个函数,该函数会被应用到每个元素上,并将其映射成一个新的元素。
flatMap:接收一个函数做参数,将流中每个值换成另一个流,然后把所有流连接成一个流。

		List<String> list1 = Arrays.asList("1,2,3", "a,s,d");
		Stream<String> s1 = list1.stream().map(s -> s.replace(",", ""));
		s1.forEach(System.out::println);

flatMap:将流中的每一个值都换成另一个流,然后把所有流连接成一个流

			Stream<String> s3=list1.stream().flatMap(s->{
			//将每个元素转换成一个stream
			String[] split = s.split(",");
			Stream<String> s2 = Arrays.stream(split);
			return s2;
		});
		s3.forEach(System.out::println);
2.3 排序

自带
也可以自己写规则:姓名相同比较年龄 如此

2.4 消费

peek() 收到的是consumer表达式 ,没有返回值 只给不往回拿

3、流的终止操作

3.1匹配聚合

allMatch:接受一个Pridicate函数,都符合才返回true

List<Integer> list1 = Arrays.asList(1, 2, 3, 4);		boolean allMatch = list1.stream().allMatch(e -> e > 10);		boolean noneMatch = list1.stream().noneMatch(e -> e > 10);		Integer findFirst = list1.stream().findFirst().get();		Integer findAny = list1.stream().findAny().get();		long count = list1.stream().count();		Integer max = list1.stream().max(Integer::compareTo).get();		Integer min = list1.stream().min(Integer::compareTo).get();
3.2 规约操作

在并行流里不理解

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24);		Integer v = list.stream().reduce((x1, x2) -> x1 + x2).get();		System.out.println(v);		Integer v3=list.parallelStream().reduce(0,(x1,x2)->{			System.out.println("acc:x1"+x1+" x2:"+x2);			return x1-x2;		},(x1,x2)->{			                             System.out.println("combine:x1"+x1+"x2:"+x2);			                             return x1*x2;		                             }		                             );		System.out.println(v3);	}
3.3 收集操作

collect:接收一个collector实例,将流中元素收集成另一个数据结构。
Collector<T,A,R>是一个接口

1.三种转换
List<Person> personList = new ArrayList<Person>();		personList.add(new Person("Tom", 8900, 23, "male", "New York"));		personList.add(new Person("Jack", 7000, 25, "male", "Washington"));		personList.add(new Person("Lily", 7800, 21, "female", "Washington"));		personList.add(new Person("Anni", 8200, 24, "female", "New York"));		personList.add(new Person("Owen", 9500, 25, "male", "New York"));		personList.add(new Person("Alisa", 7900, 26, "female", "New York"));		List<Integer> ageList = personList.stream().map(Person::getAge).collect(Collectors.toList());		System.out.println(ageList);		//装成set		Set<Person> ageSet = personList.stream().collect(Collectors.toSet());		System.out.println(ageSet);		//装成map		Map<String,Integer> personMap1 = personList.stream().collect(Collectors.toMap(Person::getName, Person::getSalary));		System.out.println(personMap1);
2.字符串分隔符连接

joining后面三个参数的意义

String joinName = personList.stream().map(Person::getName).collect(Collectors.joining(",", "(", ")"));		System.out.println(joinName);
3.4聚合操作
Long count = personList.stream().collect(Collectors.counting());		System.out.println(count);		//最大年龄		Integer maxAge = personList.stream().map(Person::getAge).collect(Collectors.maxBy(Integer::compare)).get();		System.out.println(maxAge);		//年龄总数		Integer sumAge = personList.stream().collect(Collectors.summingInt(Person::getAge));		System.out.println(sumAge);		//平均年龄		Double avgAge = personList.stream().collect(Collectors.averagingInt(Person::getAge));		System.out.println(avgAge);		//带上以上所有方法		DoubleSummaryStatistics statistics = personList.stream().collect(Collectors.summarizingDouble(Person::getAge));		System.out.println("count:"+statistics.getCount()+",max"+statistics.getMax());		//分组		Map<Integer, List<Person>> ageMap = personList.stream().collect(Collectors.groupingBy(Person::getAge));		System.out.println(ageMap);		//多层分组		Map<Integer, Map<Integer, List<Person>>> map1 =				personList.stream().collect(Collectors.groupingBy(Person::getAge,				                                                  Collectors.groupingBy(Person::getSalary)));		System.out.println(map1);		System.out.println("__");		//分区		Map<Boolean, List<Person>> collect =				personList.stream().collect(Collectors.partitioningBy(v -> v.getAge() > 10));		System.out.println(collect);		//规约		Integer integer = personList.stream().map(Person::getAge).collect(Collectors.reducing(Integer::sum)).get();		System.out.println(integer);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值