Java8新特性(三):Stream流与Stream API

Java8新特性(三):Stream流与Stream API,第1张

Java8新特性(三):Stream流与Stream API

Stream流简介

 Stream的 *** 作步骤

1、创建Stream流

2、中间流水线 *** 作

3、终止 *** 作,产生需要的结果源数据

注意:Stream流和最终产生的结果不影响

创建Stream的代码示例

List list = Arrays.asList("Sarah", "Terry", "Selina", "Tom");

// 创建Stream
@Test
public void test01(){
	// 1、通过Collection提供的stream()或者 paralleStream()
	Stream stream01 =  list.stream();

	// 2、通过Stream类的静态方法of()
	Stream stream02 = Stream.of("aa", "bb", "cc");

	// 3、通过Arrays的静态方法 stream() 获取数组流
	Stream stream03 = Arrays.stream(new Integer[]{1,1,1});

	// 4、创建无限流
	Stream stream04 = Stream.iterate(0,(x) -> x+2);
	stream04.limit(10).forEach(System.out::println);
}

 Stream的中间 *** 作:筛选与切片

代码示例:

List strList = Arrays.asList("Sarah", "Terry", "Selina", "Tom", "Selina", "Terry");

List employeeList = Arrays.asList(
		new Employee("张三",18,2000),
		new Employee("李四",58,3000),
		new Employee("王五",48,7000),
		new Employee("陈六",38,9000),
		new Employee("田七",18,9000),
		new Employee("田七",18,9000),
		new Employee("田七",18,9000)
);

//中间 *** 作


// filter
@Test
public void test01(){
	// 中间 *** 作
	Stream stream = strList.stream().filter((x) -> x.length() > 3);

	// 终止 *** 作
	stream.forEach(System.out::println);
}

// limit
@Test
public void test02(){
	employeeList.stream().limit(2).forEach(System.out::println);
}

// skip
@Test
public void test03(){
	employeeList.stream().skip(2).forEach(System.out::println);
}

// distinct
@Test
public void test04(){
	strList.stream().distinct().forEach(System.out::println);
}

// 惰性求值
@Test
public void test05(){
	employeeList.stream()
			.filter((x) -> {
				System.out.println("短路");
				return x.getAge() >50;
			})
			.limit(2)
			.forEach(System.out::println);
}

惰性求值

 

Stream的中间 *** 作:映射

代码示例

List strList = Arrays.asList("aa", "bb", "cc");

List employeeList = Arrays.asList(
		new Employee("张三",18,2000),
		new Employee("李四",58,3000),
		new Employee("王五",48,7000),
		new Employee("陈六",38,9000),
		new Employee("田七",18,9000),
		new Employee("田七",18,9000),
		new Employee("田七",18,9000)
);

//中间 *** 作


// map
@Test
public void test01(){
	employeeList.stream().map(e -> e.getName()).forEach(System.out::println);
}

// flatMap
@Test
public void test02(){
	strList.stream().map(s -> s.toUpperCase()).forEach(System.out::println);// {AA, BB, CC}
	strList.stream().flatMap(s -> filterCharacter(s)).forEach(System.out::println);// {a, a, b, b, c, c}
}

private Stream filterCharacter(String str){
	List list = new ArrayList<>();
	for (char c : str.toCharArray()) {
		list.add(c);
	}
	return list.stream();
}

  

Stream的中间 *** 作:排序

代码示例

List employeeList = Arrays.asList(
		new Employee("张三",18,2000),
		new Employee("李四",58,3000),
		new Employee("王五",48,7000),
		new Employee("陈六",38,9000),
		new Employee("田七",18,9000),
		new Employee("田七",18,9000),
		new Employee("田七",18,9000)
);

//中间 *** 作


// sorted()
@Test
public void test01(){
	employeeList.stream().map(e -> e.getAge()).sorted().forEach(System.out::println);
}

// sorted(Comparactor com)
@Test
public void test02(){
	employeeList.stream().sorted((e1, e2) -> {
	   if(e1.getAge() == e2.getAge()){
		   return e1.getName().compareTo(e2.getName());
	   }else {
		   return -Integer.compare(e1.getAge(), e2.getAge());
	   }
	}).forEach(System.out::println);
}

 

Stream的终止 *** 作:查找与匹配

 代码示例:

List employeeList = Arrays.asList(
		new Employee("张三",18,2000, Employee.Status.BUSY),
		new Employee("李四",58,3000, Employee.Status.FREE),
		new Employee("王五",48,7000, Employee.Status.VOCATION),
		new Employee("陈六",38,9000, Employee.Status.BUSY),
		new Employee("田七",18,9000, Employee.Status.BUSY),
		new Employee("王二",18,9000, Employee.Status.BUSY),
		new Employee("田七",18,9000, Employee.Status.VOCATION)
);

//终止 *** 作


// allMatch()
@Test
public void test01(){
	boolean b = employeeList.stream().allMatch((e) -> e.getStatus().equals(Employee.Status.BUSY));
	System.out.println(b);
}

// anyMatch()
@Test
public void test02(){
	boolean b = employeeList.stream().anyMatch((e) -> e.getStatus().equals(Employee.Status.BUSY));
	System.out.println(b);
}

// noneMatch()
@Test
public void test03(){
	boolean b = employeeList.stream().noneMatch((e) -> e.getStatus().equals(Employee.Status.BUSY));
	System.out.println(b);
}

// findFirst()
@Test
public void test04(){
	Optional e =  employeeList.stream().findFirst();
	System.out.println(e.get());
}

// findAny()
@Test
public void test05(){
	// parallelStream为并行流
	Optional employee =  employeeList.parallelStream().filter((e) -> e.getStatus().equals(Employee.Status.BUSY)).findAny();
	System.out.println(employee.get());

}

// count()
@Test
public void test06(){
	long count = employeeList.stream().count();
	System.out.println(count);
}

// max(Comparator com)
@Test
public void test07(){
	Optional e =  employeeList.stream().max((e1, e2) -> {
		if(e1.getAge() == e2.getAge()){
			return e1.getName().compareTo(e2.getName());
		}else {
			return Integer.compare(e1.getAge(), e2.getAge());
		}
	});
	System.out.println(e.get());
}

// min(Comparator com)
@Test
public void test08(){
	Optional e =  employeeList.stream().min((e1, e2) -> {
		if(e1.getAge() == e2.getAge()){
			return e1.getName().compareTo(e2.getName());
		}else {
			return Integer.compare(e1.getAge(), e2.getAge());
		}
	});
	System.out.println(e.get());
}

// 串行流与并行流

@Test
public void test09(){
	List numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
	numbers.stream().forEach(System.out::print);
	// 输出结果是固定的
	// 123456789

	numbers.parallelStream().forEach(System.out::print);
	// 输出结果是不固定的
	// 652879314

	//打印并查看线程信息
	numbers.parallelStream().forEach((num) -> System.out.println(Thread.currentThread().getName()+">>"+num));
	// ForkJoinPool.commonPool-worker-7>>3
	// ForkJoinPool.commonPool-worker-2>>4
	// ForkJoinPool.commonPool-worker-3>>9
	// ForkJoinPool.commonPool-worker-5>>2
	// ForkJoinPool.commonPool-worker-1>>7
	// ForkJoinPool.commonPool-worker-4>>5
	// ForkJoinPool.commonPool-worker-6>>8
	// main>>6
	// ForkJoinPool.commonPool-worker-7>>1
}

 

Stream的终止 *** 作:归约 

代码示例:

List employeeList = Arrays.asList(
		new Employee("张三",18,2000, Employee.Status.BUSY),
		new Employee("李四",58,3000, Employee.Status.FREE),
		new Employee("王五",48,7000, Employee.Status.VOCATION),
		new Employee("陈六",38,9000, Employee.Status.BUSY),
		new Employee("田七",18,9000, Employee.Status.BUSY),
		new Employee("王二",18,9000, Employee.Status.BUSY),
		new Employee("田七",18,9000, Employee.Status.VOCATION)
);

//终止 *** 作


// reduce()
@Test
public void test01(){
	List list = Arrays.asList(1,2,3,4,5,6,7,8,9);
	Integer sum = list.stream().reduce(0, (x, y) -> x+y);
	System.out.println(sum);
	// reduce中的 x+y 的执行过程
	// 0+1=1
	// 1+2=3
	// 3+3=6
	// ...
	// 36+9=45
}

@Test
public void test02(){
	Optional sum = employeeList.stream().map(e -> e.getAge()).reduce((x, y) -> x+y);
	System.out.println(sum.get());
}

Stream的终止 *** 作:内部迭代

 Stream的终止 *** 作:收集

 

Collector中的方法实现了对流的收集 *** 作(如收集到List、Set、Map)。

Collectors实用类提供了很多静态方法,可以方便地创建收集器实例。

代码示例:

List employeeList = Arrays.asList(
		new Employee("张三",18,2000, Employee.Status.BUSY),
		new Employee("李四",58,3000, Employee.Status.FREE),
		new Employee("王五",48,7000, Employee.Status.VOCATION),
		new Employee("陈六",38,9000, Employee.Status.BUSY),
		new Employee("田七",18,9000, Employee.Status.BUSY),
		new Employee("王二",18,9000, Employee.Status.BUSY),
		new Employee("田七",18,9000, Employee.Status.VOCATION)
);

//终止 *** 作


// reduce()
@Test
public void test01(){
	List list = employeeList.stream().map(Employee::getName).collect(Collectors.toList());
	list.forEach(System.out::println);

	System.out.println("-----------------------");

	Set set = employeeList.stream().map(Employee::getName).collect(Collectors.toSet());
	set.forEach(System.out::println);

	System.out.println("-----------------------");

	HashSet hs = employeeList.stream().map(Employee::getName).collect(Collectors.toCollection(HashSet::new));
	hs.forEach(System.out::println);
	//等同于以下的写法
	HashSet hashSet = employeeList.stream().map(Employee::getName).collect(Collectors.toCollection(new Supplier>() {
		@Override
		public HashSet get() {
			return new HashSet<>();
		}
	}));
	hashSet.forEach(System.out::println);
}

// 求和、求平均值、求最大值、求最小值
@Test
public void test02(){
	// 求所有age的平均值
	Double ave = employeeList.stream().collect(Collectors.averagingInt(Employee::getAge));

	// 求所有age的总和
	Integer sum = employeeList.stream().collect(Collectors.summingInt(Employee::getAge));

	// 求age最大的Employee
	Optional max = employeeList.stream()
			.collect(Collectors.maxBy((o1, o2) -> Integer.compare(o1.getAge(), o2.getAge())));

	// 求age最小的Employee
	Optional min = employeeList.stream().collect(Collectors.minBy((o1, o2) -> Integer.compare(o1.getAge(), o2.getAge())));
}

// 分组
@Test
public void test03(){
	Map> map = employeeList.stream().collect(Collectors.groupingBy(Employee::getStatus));
}

// 多级分组
@Test
public void test04(){
	Map>> map = employeeList.stream().collect(Collectors.groupingBy(Employee::getStatus, Collectors.groupingBy((e) -> {
		if(e.getAge() <= 35){
			return "青年";
		}else if((e.getAge() >= 35) &&  (e.getAge()<= 50)){
			return "中年";
		}else {
			return "老年";
		}
	})));
	System.out.println(map);
}

// 分区
@Test
public void test05(){
	Map> map = employeeList.stream().collect(Collectors.partitioningBy(e -> e.getSalary() > 8000));
	System.out.println(map);
}

@Test
public void test06(){
	DoubleSummaryStatistics dss = employeeList.stream().collect(Collectors.summarizingDouble(Employee::getSalary));
	System.out.println(dss.getMax());
	System.out.println(dss.getAverage());
	System.out.println(dss.getMin());
	System.out.println(dss.getSum());
}

@Test
public void test07(){
	String str = employeeList.stream().map(Employee::getName).collect(Collectors.joining(",", "--", "++"));
	System.out.println(str);
}

 

 

 

 

 

 

 

 

 

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/4019412.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-10-22
下一篇 2022-10-22

发表评论

登录后才能评论

评论列表(0条)

保存