基于list stream: reduce的使用实例
作者:互联网
目录
- list stream: reduce的使用
- reduce 一共有三种实现
- 1、第一种
- 2、第二种
- 3、第三种
- reduce 一共有三种实现
- reduce的基本用法
- 1、初识 reduce 的基本 api
- 2、应用场景测试
list stream: reduce的使用
stream 中的 reduce 的主要作用就是stream中元素进行组合,组合的方式可以是加减乘除,也可以是拼接等,接下来我们就通过实例来看一下reduce的用法:
reduce 一共有三种实现
1、第一种
?1 |
T reduce(T identity, BinaryOperator accumulator);
|
该实现有起始值 identity, 起始值的类型决定了返回结果的类型,通过 accumulator 操作最终得到 identity 类型的返回结果
2、第二种
?1 |
Optional<T> reduce(BinaryOperator accumulator);
|
该实现只有一个参数 accumulator , 由于没有办法确定具体的返回结果,所以该方法返回的是 Optional
3、第三种
?1 |
<U> U reduce(U identity, BiFunction<U, ? super T, U> accumulator, BinaryOperator<U> combiner);
|
该方法有三个参数 identity 、 accumulator 、combiner ,该方法通过 identity 和 accumulator的处理得出最终结果,结果和第一个参数的类型相同
首先把我们下面操作的这个实体对象先放在这里
?1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
pulbic class User {
//ID
private Long id;
//年龄
private int age;
//班级
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 + '\ '' +
'}' ;
}
|
用来求和,如下所示是四种不同的方式来获取User对象中的age只和,其中两种是通过reduce来进行求和
?1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
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);
|
用来求最大最小值,如下所示是求User中age的最大最小值
?1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
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);
}
|
用来拼接字符串,如下所示:
?1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
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( "拼接字符串:" , String::concat);
System.out.println( "append : " + append);
}
|
计算平均值:计算User对象中age字段的平均值
?1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
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);
}
|
reduce的基本用法
1、初识 reduce 的基本 api
?1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
@Test
public void testReduce() {
Stream<Integer> stream = Arrays.stream( new Integer[]{ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 });
//求集合元素只和
Integer result = stream.reduce( 0 , Integer::sum);
System.out.println(result);
stream = Arrays.stream( new Integer[]{ 1 , 2 , 3 , 4 , 5 , 6 , 7 });
//求和
stream.reduce((i, j) -> i + j).ifPresent(System.out::println);
stream = Arrays.stream( new Integer[]{ 1 , 2 , 3 , 4 , 5 , 6 , 7 });
//求最大值
stream.reduce(Integer::max).ifPresent(System.out::println);
stream = Arrays.stream( new Integer[]{ 1 , 2 , 3 , 4 , 5 , 6 , 7 });
//求最小值
stream.reduce(Integer::min).ifPresent(System.out::println);
stream = Arrays.stream( new Integer[]{ 1 , 2 , 3 , 4 , 5 , 6 , 7 });
//做逻辑
stream.reduce((i, j) -> i > j ? j : i).ifPresent(System.out::println);
stream = Arrays.stream( new Integer[]{ 1 , 2 , 3 , 4 , 5 , 6 , 7 });
//求逻辑求乘机
int result2 = stream.filter(i -> i % 2 == 0 ).reduce( 1 , (i, j) -> i * j);
Optional.of(result2).ifPresent(System.out::println);
}
|
2、应用场景测试
求所有学生的成绩之和。
?1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
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();
//使用Reduce 将所有的所有的成绩进行加和
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();
//使用Reduce 求 list 、student 的总成绩之和
Score scoreSum = list.stream()
.map(Student::getScore)
//相当于加了一个初始值
.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;
}
}
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
package com.jd.bean;
//学生
public class Student {
private Integer id;
//课程分数
private Score score;
public int getId() {
return id;
}
public void setId( int id) {
this .id = id;
}
public Score getScore() {
return score;
}
public void setScore(Score score) {
this .score = score;
}
}
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
package com.jd.bean;
//课程分数
public class Score {
//分数
private Integer point;
//课程名称
private String courseName;
public Integer getPoint() {
return point;
}
public Score add(Score other) {
this .point += other.getPoint();
return this ;
}
public void setPoint(Integer point) {
this .point = point;
}
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this .courseName = courseName;
}
}
|
以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://zhangzehai.blog.csdn.net/article/details/106369542
标签:stream,list,reduce,userList,User,new,public 来源: https://www.cnblogs.com/tiancai/p/16623124.html