New features of java8 - use of stream API

Keywords: Java api stream

Operation steps of Stream

1. Create a Stream
Get a stream through a data source (such as a collection or array)
2. Intermediate operation
Intermediate operation chain: operate the data of the data source
3. Terminate the operation
Execute the intermediate operation chain and produce results

Create Stream

1. You can use the stream() or parallelStream() provided by the Collection series Collection
2. Obtain the array stream through the static method stream() in Arrays
3. Pass the static method of() in the Stream class
4. Create an infinite stream

//1. You can use the stream() or parallelStream() provided by the Collection series Collection
List<String> list = new ArrayList<>();
Stream<String> stream1 = list.stream();​
//2. Obtain the array stream through the static method stream() in Arrays
Employee[] emps = new Employee[10];
Stream<Employee> stream2 = Arrays.stream(emps);​
//3. Pass the static method of() in the Stream class
Stream<String> stream3 = stream.of("aa","bb","cc");​
//4. Create an infinite stream
//iteration
Stream<Integer> stream4 = Stream.iterate(0,(x) -> x+2 );
stream4.limit(10).forEach(System.out::println);​
//generate
Stream.generate(() -> Math.random())      
	.limit(5)      
	.forEach(System.out::println);

Intermediate operation

1. Screening and slicing

filter ---- receive Lambd and exclude some elements from the stream
limit ------ truncate the flow so that its elements do not exceed the given number
skip(n) -- skip elements and return a stream that throws away the first n elements. If there are less than n elements in the stream, an empty stream is returned. Complementary to limit(n)
distinct - filter and remove duplicate elements through hashCode() and equals() of the elements generated by the stream (the hashCode and equals methods need to be rewritten)

List<Employee> employees = Arrays.asList(
		new Employee("Zhang San",18,9999.99),
		new Employee("Li Si",58,5555.55),
		new Employee("Wang Wu",26,3333.33),
		new Employee("Zhao Liu",36,6666.66),
		new Employee("pseudo-ginseng",12,8888.88),
  	new Employee("pseudo-ginseng",12,8888.88),
  	new Employee("pseudo-ginseng",12,8888.88),
  	new Employee("pseudo-ginseng",12,8888.88),
);

//Use of filter: filter out those over 35 years old in the effluent
//Intermediate operation: no operation will be performed
Stream<Employee> stream = employees.strem()
  						.filter((e) -> {
                              System.out.println("Stream API Intermediate operation of");
                              return e.getAge() > 35;
                            });
//Terminate operation: all operations are performed at one time, i.e. "inert operation"
stream.forEach(System.out::println);


//Use of limit: filter out the first two with salary greater than 5000
employees.stream()
  		 .filter((e) -> {
           System.out.println("Short circuit!");
           return e.getSalary() > 5000;
         })
  		 .limit(2)
  		 .forEach(System.out::println);


//Use of skip: throw out the first two filtered salaries greater than 5000
employees.stream()
  			 .filter((e) -> {
           System.out.println("Short circuit!");
           return e.getSalary() > 5000;
         })
  			 .skip(2)
  			 .forEach(System.out::println);


//Use of distinct: filter out the salary greater than 5000, then throw away the first two elements, and finally remove the duplicate elements
employees.stream()
  		.filter((e) -> {
           System.out.println("Short circuit!");
           return e.getSalary() > 5000;
         })
  		.skip(2)
  	    .distinct()
  		.forEach(System.out::println);
//Note: the hashCode method and equals method of the Employee class need to be overridden

2. Mapping

map ---- receive Lambda, convert elements into other forms or extract information. Receive a function as an argument, which is applied to each element and mapped to a new element
flatMap ---- receive a function as a parameter, change each value in the stream to another stream, and then return the new stream

List<String> list = Arrays.asList("aaa","bbb","ccc","ddd","eee");

List<Employee> employees = Arrays.asList(
		new Employee("Zhang San",18,9999.99),
		new Employee("Li Si",58,5555.55),
		new Employee("Wang Wu",26,3333.33),
		new Employee("Zhao Liu",36,6666.66),
		new Employee("pseudo-ginseng",12,8888.88)
);


//Use of map: convert each element to uppercase
list.stream()
  	.map((str) -> str.toUpperCase())
  	.forEach(System.out::println);

//Use of map: get the name of each element
employees.stream()
  			 .map(Employee::getName)
  			 .forEach(System.out::println);


public static Stream<Character> filterCharacter(String str){
  List<Character> list = new ArrayList<>();
  for(Character ch : str.toCharArray()){
    list.add(ch);
  }
  return list.stream();
}

//Method 1: use map: each element obtained corresponds to a stream
Stream<Stream<Character>> stream = list.stream()
  			.map(TestStreamApI::filterCharacter);
stream.forEach((sm) -> {
  sm.forEach(System.out::println);
});

//Method 2: use flatMap: get a stream
Stream<Character> sm = list.stream()
  			.flatmap(TestStreamApI::filterCharacter);
sm.forEach(System.out::println);

3. Sorting

sorted() -------- comparable
sorted(Comparator com) -- customized sorting (Comparator)

List<String> list = Arrays.asList("ccc","aaa","bbb","ddd","eee");

List<Employee> employees = Arrays.asList(
		new Employee("Zhang San",18,9999.99),
		new Employee("Li Si",58,5555.55),
		new Employee("Wang Wu",26,3333.33),
		new Employee("Zhao Liu",36,6666.66),
		new Employee("pseudo-ginseng",12,8888.88)
);

//Use of natural sorting
list.stream()
  	.sorted()
  	.forEach(System.out::println);

//Use of custom sorting
employees.stream()
  			 .sorted((e1,e2) -> {
						if(e1.getAge().equals(e2.getAge())){
              	return e1.getName().compareTo(e2.getName());
            }else{
              	return e1.getAge().compareTo(e2.getAge());
            }
         }).forEach(System.out::println);

Terminate operation

1. Find and match

allMatch --------------- check whether all elements match
anyMatch --------------- check to see if at least one element matches
noneMatch ------- check whether all elements are not matched
findFirst -------- returns the first element
findAny ----------------- returns any element in the current stream
count ----------------- returns the total number of elements in the stream
max ------------ returns the maximum value in the stream
min ------------ returns the minimum value in the stream

List<Employee> employees = Arrays.asList(
		new Employee("Zhang San",18,9999.99,Status.FREE),
		new Employee("Li Si",58,5555.55,Status.BUSY),
		new Employee("Wang Wu",26,3333.33,Status.VOCATION),
		new Employee("Zhao Liu",36,6666.66,Status.FREE),
		new Employee("pseudo-ginseng",12,8888.88,Status.BUSY)
);

//Use of allMatch
boolean b1 = employees.stream()
  						.allMatch((e) -> e.getStatus().equals(Status.BUSY));
System.out.println(b1);

//Use of anyMatch
boolean b2 = employees.stream()
  						.anyMatch((e) -> e.getStatus().equals(Status.BUSY));
System.out.println(b2);

//Use of noneMatch
boolean b3 = employees.stream()
  						.noneMatch((e) -> e.getStatus().equals(Status.BUSY));
System.out.println(b3);

//Use of findFirst
Optional<Employee> op = employees.stream()
  				.sorted((e1,e2) -> Double.compare(e1.getSalary(),e2.getSalary()))
  				.findFirst();
System.out.println(op.get());

//Use of findAny
Optional<Employee> op2 = employees.stream()
  				.filter((e) -> e.getStatus().equals(Status.FREE))
  				.findAny();
System.out.println(op2.get());

//Use of count
Long count = employees.stream()
  						.count();
System.out.println(count);

//Use of max
Optional<Employee> op1 = employees.stream()
  								.max((e1,e2) -> Double.compare(e1.getSalary(),e2.getSalary()));
System.out.println(op1.get());

//Use of min
Optional<Employee> op2 = employees.stream()
  								.map(Employee::getSalary)
  								.min(Double::compare);
System.out.println(op2.get());

2. Reduction

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

List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);

//Mode 1
//Use of reduce: take the 0th element as x, the 1st element as y, its sum value as x again, the 2nd element as y, and combine repeatedly to get a value
Integer sum = list.stream()
			.reduce(0,(x,y) -> x+y);
System.out.println(sum);

//Mode II
//Use of reduce
Optional<Double> op = employees.stream()
  						.map(Employee::getSalary)
  						.reduce(Double::sum);
System.out.println(op.get());

3. Collection

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

//Use of collect: convert to list
List<String> list = employees.stream()
						.map(Employee::getName)
						.collect(Collectors.toList());
list.forEach(System.out::println);

//Use of collect: convert to set
Set<String> set = employees.stream()
						.map(Employee::getName)
						.collect(Collectors.toSet());
set.forEach(System.out::println);

//Use of collect: convert to hashSet
HashSet<String> hs = employees.stream()
						 .map(Employee::getName)
				 		 .collect(Collectors.toCollection(HashSet::new));
hs.forEach(System.out::println);

Posted by shan169 on Wed, 13 Oct 2021 20:53:27 -0700