Use example based on list stream: reduce
- 2021-11-10 09:44:59
- OfStack
list stream: Use of reduce
The main function of reduce in stream is to combine the elements in stream, which can be addition, subtraction, multiplication and division, splicing, etc. Next, we will look at the usage of reduce under 1 through examples:
There are three implementations of reduce 1
1. Type 1
T reduce(T identity, BinaryOperator accumulator);
The implementation has a starting value identity, and the type of the starting value determines the type of the return result. Finally, the return result of identity type is obtained through accumulator operation
2. Type 2
Optional<T> reduce(BinaryOperator accumulator);
This implementation has only one parameter accumulator, and because there is no way to determine the specific return result, this method returns Optional
3. Type 3
<U> U reduce(U identity, BiFunction<U, ? super T, U> accumulator, BinaryOperator<U> combiner);
The method has three parameters identity, accumulator and combiner. The final result is obtained by processing identity and accumulator. The type of the result is the same as that of the first parameter
First, put the entity object that we operate on below here
pulbic class User {
//ID
private Long id;
// Age
private int age;
// Class
private String classes;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getClasses() {
return classes;
}
public void setClasses(String classes) {
this.classes = classes;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", age=" + age +
", classes='" + classes + '\'' +
'}';
}
Used to sum, the following are four different ways to get the age sum in the User object, two of which are summed through reduce
List<User> userList = new ArrayList<>();
User user1 = new User();
user1.setAge(10);
userList.add(user1);
User user2 = new User();
user2.setAge(20);
userList.add(user2);
User user3 = new User();
user3.setAge(25);
userList.add(user3);
int ageSumThree = userList.stream().map(User::getAge).reduce(0, Integer::sum);
System.out.println("ageSumThree: " + ageSumThree);
int ageSumFive = userList.stream().map(User::getAge).reduce(Integer::sum).orElse(0);
System.out.println("ageSumFive: " + ageSumFive);
int ageSumOne = userList.stream().collect(Collectors.summingInt(User::getAge));
System.out.println("ageSumOne" + ageSumOne);
int ageSumFour = userList.stream().mapToInt(User::getAge).sum();
System.out.println("ageSumFour: " + ageSumFour);
Used to find the maximum and minimum value, as shown below is to find the maximum and minimum value of age in User
public static void main(String[] args) {
List<User> userList = new ArrayList<>();
User user1 = new User();
user1.setAge(10);
userList.add(user1);
User user2 = new User();
user2.setAge(20);
userList.add(user2);
User user3 = new User();
user3.setAge(25);
userList.add(user3);
User user4 = new User();
user4.setAge(25);
userList.add(user4);
int min = userList.stream().map(User::getAge).reduce(Integer::min).orElse(0);
System.out.println("min : " + min);
int max = userList.stream().map(User::getAge).reduce(Integer::max).orElse(0);
System.out.println("max : " + max);
}
Used to splice strings, as follows:
public static void main(String[] args) {
List<User> userList = new ArrayList<>();
User user1 = new User();
user1.setAge(10);
userList.add(user1);
User user2 = new User();
user2.setAge(20);
userList.add(user2);
User user3 = new User();
user3.setAge(25);
userList.add(user3);
User user4 = new User();
user4.setAge(25);
userList.add(user4);
String append = userList.stream().map(User::toString).reduce(" Splice string: ", String::concat);
System.out.println("append : " + append);
}
Calculate Average: Calculate the average value of the age field in the User object
public static void main(String[] args) {
List<User> userList = new ArrayList<>();
User user1 = new User();
user1.setAge(10);
userList.add(user1);
User user2 = new User();
user2.setAge(20);
userList.add(user2);
User user3 = new User();
user3.setAge(25);
userList.add(user3);
User user4 = new User();
user4.setAge(25);
userList.add(user4);
double average = userList.stream().mapToInt(User::getAge).average().orElse(0.0);
System.out.println("average : " + average);
}
Basic Usage of reduce
1. First know the basic api of reduce
@Test
public void testReduce() {
Stream<Integer> stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7, 8});
// Find only the sum of set elements
Integer result = stream.reduce(0, Integer::sum);
System.out.println(result);
stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});
// Summation
stream.reduce((i, j) -> i + j).ifPresent(System.out::println);
stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});
// Find the maximum
stream.reduce(Integer::max).ifPresent(System.out::println);
stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});
// Find the minimum
stream.reduce(Integer::min).ifPresent(System.out::println);
stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});
// Do logic
stream.reduce((i, j) -> i > j ? j : i).ifPresent(System.out::println);
stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});
// Seek logic and take advantage of it
int result2 = stream.filter(i -> i % 2 == 0).reduce(1, (i, j) -> i * j);
Optional.of(result2).ifPresent(System.out::println);
}
2. Application scenario testing
Seek the sum of all students' grades.
package com.jd;
import com.jd.bean.Score;
import com.jd.bean.Student;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;
/**
* @author: wangyingjie1
* @version: 1.0
* @createdate: 2017-09-26 09:35
*/
public class ReduceTest {
@Test
public void reduceList() {
List<Student> list = getStudents();
// Use Reduce Add up all the grades
Optional<Score> totalScore = list.stream()
.map(Student::getScore)
.reduce((x, y) -> x.add(y));
System.out.println(totalScore.get().getPoint());
}
@Test
public void reduceList2() {
List<Student> list = getStudents();
Student student = getStudent();
// Use Reduce Seek list , student The sum of the total scores of
Score scoreSum = list.stream()
.map(Student::getScore)
// Equivalent to adding 1 Initial values
.reduce(student.getScore(), (x, y) -> x.add(y));
System.out.println(scoreSum.getPoint());
}
private Student getStudent() {
Student student = new Student();
student.setId(4);
Score score = new Score();
score.setPoint(100);
student.setScore(score);
return student;
}
private List<Student> getStudents() {
List<Student> list = new ArrayList<>();
for (int i = 0; i < 3; i++) {
Student stu = new Student();
Score score = new Score();
score.setPoint(80);
score.setCourseName("English");
stu.setId(i);
stu.setScore(score);
list.add(stu);
}
return list;
}
}
Optional<T> reduce(BinaryOperator accumulator);
0
Optional<T> reduce(BinaryOperator accumulator);
1