Java8 Stream and lambda usage

Posted by dpluth on Tue, 21 Dec 2021 07:08:42 +0100

Stream

It is used to perform various operations and operations on the data in the collection, such as filtering, sorting, mapping... Finally get the result

The collection focuses on the storage of data, and the Stream stream focuses on the operation and operation of the data stored in the collection

Use steps

Gets the object of a Stream stream

Stream<Student> stream = 1 ist. stream() ;

  1. Call the relevant methods of the flow object to complete the intermediate operation (processing) filter on the data in the collection

Note: the intermediate operation returns a new stream object that holds the operation result

The Stream object itself cannot store any data, but can only be used to calculate the data

The intermediate operation will be delayed until the operation is terminated

Intermediate operations do not affect the data source

3. Call the termination operation method of the flow object (the final processing of the operation result) forEach

Common intermediate operation methods:

● the filter (predict pre) parameter describes the filtering conditions

● sorted() is used to sort the elements in the set

● skip(longn): skip the first few

● limit (long n): limit the first few elements to be acquired

● distinct(): used to de duplicate elements in the set, and determine whether to duplicate elements according to the results of hashCode and equals methods

● map): the map is used to extract part of the information of the element. When it is used, a Function interface type parameter needs to be passed in

Note: the type of elements held in the flow will change after the map operation

Common termination operations:

● forEach(Consumer con): traverse the final operation result

● allmatch (predict) determines whether all elements in the set meet a - specified condition

The code is as follows:

	public static void main(String[] args) {
		List<Employee> list=new ArrayList<Employee>();
		Stream<Employee> stream=list.stream();
		list.add(new Employee("1","Hu Ge","male",20000,PizzaStatus.busy));
		list.add(new Employee("2","Liu Yifei","female",30000,PizzaStatus.free));
		list.add(new Employee("3","Yang Mi","female",50000,PizzaStatus.busy));
		list.add(new Employee("4","Yang Yang","male",10000,PizzaStatus.free));
		list.add(new Employee("5","Li Yifeng","male",15000,PizzaStatus.leave));
		list.add(new Employee("6","Mao Bu Yi","male",1500,PizzaStatus.leave));
		list.add(new Employee("7","Wang Zong","male",90000,PizzaStatus.free));
		//Find male employees with an output salary of more than 6000 yuan
//		stream. filter(s->s.getEmpGender(). Equals ("male") & & s.getempsalary() > 6000) forEach(System.out::println);;
		//Displays the information of the employee with the lowest salary
//		Optional<Employee> opt=stream.min((s1,s2 )->(int)(s1.getEmpSalary()-s2.getEmpSalary()));
//		System.out.println(opt.get());
		//Display maximum wage
//		Optional<Double> opts=stream.map(s->s.getEmpSalary()).max((a1,a2)->(int)(a1-a2));
//		System.out.println(opts.get());
		//Calculate the average salary of all employees
//		Double collect=stream.collect(Collectors.averagingDouble(s->s.getEmpSalary()));
//		System.out.println(collect);
		//Find and display the employee names of all resigned employees
//		stream.filter( s->s.getEmpStatus().equals(PizzaStatus.leave) ).map(s->s.getEmpName()).forEach(System.out::println);
		//Find all employees surnamed Wang and collect them into a set set
//		Set<Employee> collect=stream. filter(s->s.getEmpName(). Startswith ("Wang") collect(Collectors.toSet());
//		for (Employee e : collect) {
//			System.out.println(e);
//		}
		//Group employees according to their status information and get a map set
		Map<PizzaStatus, List<Employee>> map=stream.collect(Collectors.groupingBy(s->s.getEmpStatus()));
		for (PizzaStatus p : map.keySet()) {
			System.out.println("Status:"+p);
			List<Employee> emp=map.get(p);
			for (Employee e : emp) {
				System.out.println("\t"+e);
			}
			System.out.println(emp.size());
		}
		//Traverse this result and output the number of people in each state
		
	}

}
class Employee{
	private String empld;
	private String empName;
	private String empGender;
	private double empSalary;
	private PizzaStatus empStatus;
	public enum PizzaStatus{
		busy,
		free,
		leave;
	
	}
	public String getEmpld() {
		return empld;
	}
	public void setEmpld(String empld) {
		this.empld = empld;
	}
	public String getEmpName() {
		return empName;
	}
	public void setEmpName(String empName) {
		this.empName = empName;
	}
	public String getEmpGender() {
		return empGender;
	}
	public void setEmpGender(String empGender) {
		this.empGender = empGender;
	}
	public double getEmpSalary() {
		return empSalary;
	}
	public void setEmpSalary(double empSalary) {
		this.empSalary = empSalary;
	}
	public PizzaStatus getEmpStatus() {
		return empStatus;
	}
	public void setEmpStatus(PizzaStatus empStatus) {
		this.empStatus = empStatus;
	}
	public Employee(String empld, String empName, String empGender, double empSalary, PizzaStatus empStatus) {
		super();
		this.empld = empld;
		this.empName = empName;
		this.empGender = empGender;
		this.empSalary = empSalary;
		this.empStatus = empStatus;
	}
	@Override
	public String toString() {
		return "Employee [empld=" + empld + ", empName=" + empName + ", empGender=" + empGender + ", empSalary="
				+ empSalary + ", empStatus=" + empStatus + "]";
	}
	
}

There is a more detailed article on the Internet. I'll send it to you for a look. I hope it can help you and add a little more lambda knowledge

https://zhuanlan.zhihu.com/p/429885334https://zhuanlan.zhihu.com/p/429885334https://zhuanlan.zhihu.com/p/429885334 Let me add a little more knowledge about lambda. It's very convenient

Lambda expression

Premise of Lambda expression:

  • There must be an interface (not an abstract class), and there is only one abstract method in the interface that needs to be overridden.
  • Context derivation must be supported. It is necessary to be able to deduce which interface the Lambda expression represents.

You can use the interface as a parameter and then pass a Lambda expression (commonly used), or you can assign a Lambda expression to a variable of interface type

Lambda syntax:

(parameter list) - > {lambda method body}

The type of parameter list can be omitted

If there is only one parameter in the parameter list, the parameter parentheses can be omitted. Note: if the number of parameters is 2 or more or 0, the parentheses cannot be omitted

If there is only one return statement in the lambda body, the braces in the method body and the semicolon of return and method code can be omitted

features:

  • Optional type declaration: there is no need to declare parameter types, and the compiler can uniformly identify parameter values.
  • Optional parameter parentheses: one parameter does not need to define parentheses, but multiple parameters need to define parentheses.
  • Optional curly braces: if the body contains a statement, curly braces are not required.
  • Optional return keyword: if the body has only one expression return value, the compiler will automatically return the value. Braces need to specify that the expression returns a value.

Lambda expressions can only refer to outer local variables marked final, which means that local variables defined outside the domain cannot be modified inside lambda, otherwise compilation errors will occur.

The local variable of lambda expression can not be declared as final, but it must not be modified by the following code (that is, it has implicit final semantics)

It is not allowed to declare a parameter or local variable with the same name as a local variable in a Lambda expression.

4 core functional interfaces, which are defined in Java util. Function package

  • Consumer < T >: there is an abstract method accept in the interface. The feature has a parameter with no return value void accept (T); Consumption type
  • Supplier < T >: there is an abstract method get() in the interface, which is characterized by no parameter and a return type T get(); Supply type
  • Function < T, s > this interface defines an abstract method apply, which is characterized by a parameter and a return value r apply (T, t); Functional type
  • Predict < T > an abstract method test is defined in the interface, which is characterized by a parameter and a return value. The return type is fixed as boolean test (T, t); Assertion type

Method reference: another form of Lambda

Syntax: Object Name:: instance method name or class name:: static method name

Note: the parameter type and return type of the referenced method must be consistent with the abstract method definition in the interface

Topics: Java Eclipse JavaEE Interview Programmer