About the common usage of Stream API in JDK8

Stream API

​ Generate a brand new stream, which has nothing to do with the data source (the data source is not affected)

a) Create stream method:

​ 1)collection 例如:new ArrayList<>().stream()

​ 2) Arrays.stream()

​ 3) Through the static method of () in the Stream class

​ 4) Create an infinite stream

//创建无线流 — 迭代方式
@Test
public void test1() {
    
    
	Stream<Integer> stream = Stream.iterate(0,(x) -> x+2);
	stream.limit(10).forEach(System.out::println);
}
//创建无线流  ——生成
	@Test
	public void test2() {
    
    
		Stream.generate(() ->Math.random()).limit(5).forEach(System.out::println);
	}

b) Intermediate operation

​ 1) Screening and slicing

filter-Receive Lambda and exclude certain elements from the stream.

@Test
public void test3() {
    
    //stream有内部迭代
	//中间操作
	Stream<Employee> stream = emplpoyees.stream().filter((e) ->{
    
    //filter就是中间操作
		System.out.println("开始执行判断");
		return e.getAge()>35;
	});
	/**
	终止操作:一次性执行全部内容,就是“惰性求值”;
	例如:在没有进行终止操作的情况下所有的中间操作都不会执行,只有当执行了终止操作,中间操作才会全部一次性执行!!
	**/
	stream.forEach(System.out::println);//打印就是终止操作!
}

limit——Truncate the flow so that its elements do not exceed the given number

@Test
public void test3() {
    
    
	//中间操作
	Stream<Employee> stream = emplpoyees.stream().filter((e) ->{
    
    
		System.out.println("开始执行判断");
		return e.getAge()>35;
	}).limit(1).forEach(System.out::println);//限制为1条
}

skip(n)-Skip elements. For example, there are five elements in the set. Skip(2) skips the first two and leaves the last three; if there are less than n elements in the stream, an empty stream is returned. Complementary to limit(n)

distinct——Filtering (de-duplication), removing duplicate elements through the elements hashcode() and equals() generated by the stream

​ 2) Map

​ map——Receive lambda, transform elements into other forms or extract information. Receive a function as a parameter, the function will be applied to each element, and map it into a new element.

​ flatMap——Receive a function as a parameter, replace each value in the stream with another stream, and then connect all the streams into one stream.

//映射
@Test
public void test4() {
    
    
	emplpoyees.stream().map(Employee::getName).forEach(System.out::println);
	}

​ 3) Sort

​ sorted(): Natural sorting (Comparable)

@Test
	public void test5() {
    
    
		List<String> list1 = Arrays.asList("bbb","ccc","aaa","ddd");
		list1.stream().sorted().forEach(System.out::println);
	}

​ sorted (Comparator com): custom sorting

c) Terminate operation

The following are various methods commonly used to terminate operations:

​	allMatch

​	anyMatch

​	noneMatch

​	findFirst

​	findAny

​	count

​	max

​	min

d) Statute

​ reduce(T identity,BinaryOperator) / reduce(BinaryOperator) can combine the elements in the stream repeatedly to get a value.

@Test
public void test1() {
    
    
	List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
	// T reduce(T identity, BinaryOperator<T> accumulator);
	Integer sum = list.stream().reduce(0, (x,y) -> x+y);
	System.out.println(sum);//55
    
    //需求:获取员工类中的所有工资的总和(map-reduce规约实现)
    Optional<Double> op = emplpoyees.stream().map(Employee::getSarlary).reduce(Double::sum);
		System.out.println(op.get());
}

e) Collection

​ collect-convert the stream to other forms. Receive an implementation of the Collector interface, which is used to summarize the elements in the Stream

//需求:将员工类中的所有名字收集到集合list中
public void test2() {
    
    
    /**
    	Employee::getName(方法引用的第三种方式————类::实例方法名);实例方法就是非静态方法
    	Collectors这是一个集合收集的工具类,里边包含了许多静态方法
    */
	List<String> list = emplpoyees.stream().map(Employee::getName).collect(Collectors.toList());
	list.forEach(System.out::println);
}
//set实现上一个需求(set可以将员工集合中的重复名字的员工去重)
@Test
public void test3() {
    
    
	Set<String> set = emplpoyees.stream().map(Employee::getName).collect(Collectors.toSet());
	set.forEach(System.out::println);
}
//
@Test
public void test4() {
	Long count = emplpoyees.stream().collect(Collectors.counting());
	System.out.println(count);
	
	Double avg = emplpoyees.stream().collect(Collectors.averagingDouble(Employee::getSarlary));
	System.out.println(avg);
	
	Double sum = emplpoyees.stream().collect(Collectors.summingDouble(Employee::getSarlary));
	System.out.println(sum);
}

​ In addition to the above collection methods, there are groupingBy (multi-level grouping), partitioningBy (partitioning), joining (joining) and other methods. API documents can be queried according to requirements.

Guess you like

Origin blog.csdn.net/weixin_45496190/article/details/106970254