欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

基于list stream: reduce的使用實(shí)例

 更新時(shí)間:2021年09月09日 08:45:06   作者:有夢(mèng)想的攻城獅  
這篇文章主要介紹了list stream: reduce的使用實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

list stream: reduce的使用

stream 中的 reduce 的主要作用就是stream中元素進(jìn)行組合,組合的方式可以是加減乘除,也可以是拼接等,接下來(lái)我們就通過(guò)實(shí)例來(lái)看一下reduce的用法:

reduce 一共有三種實(shí)現(xiàn)

1、第一種

T reduce(T identity, BinaryOperator accumulator);

該實(shí)現(xiàn)有起始值 identity, 起始值的類型決定了返回結(jié)果的類型,通過(guò) accumulator 操作最終得到 identity 類型的返回結(jié)果

2、第二種

Optional<T> reduce(BinaryOperator accumulator);

該實(shí)現(xiàn)只有一個(gè)參數(shù) accumulator , 由于沒(méi)有辦法確定具體的返回結(jié)果,所以該方法返回的是 Optional

3、第三種

<U> U reduce(U identity, BiFunction<U, ? super T, U> accumulator, BinaryOperator<U> combiner);

該方法有三個(gè)參數(shù) identity 、 accumulator 、combiner ,該方法通過(guò) identity 和 accumulator的處理得出最終結(jié)果,結(jié)果和第一個(gè)參數(shù)的類型相同

首先把我們下面操作的這個(gè)實(shí)體對(duì)象先放在這里

pulbic class User {
  //ID
  private Long id;
  //年齡
  private int age;
  //班級(jí)
  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 + '\'' +
      '}';
  }

用來(lái)求和,如下所示是四種不同的方式來(lái)獲取User對(duì)象中的age只和,其中兩種是通過(guò)reduce來(lái)進(jìn)行求和

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);

用來(lái)求最大最小值,如下所示是求User中age的最大最小值

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);
}

用來(lái)拼接字符串,如下所示:

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);
}

計(jì)算平均值:計(jì)算User對(duì)象中age字段的平均值

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、初識(shí) reduce 的基本 api

    @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});
        //求邏輯求乘機(jī)
        int result2 = stream.filter(i -> i % 2 == 0).reduce(1, (i, j) -> i * j);
        Optional.of(result2).ifPresent(System.out::println);
    }

2、應(yīng)用場(chǎng)景測(cè)試

求所有學(xué)生的成績(jī)之和。

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 將所有的所有的成績(jī)進(jìn)行加和
        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 的總成績(jī)之和
        Score scoreSum = list.stream()
                .map(Student::getScore)
                //相當(dāng)于加了一個(gè)初始值
                .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;
    }
}
package com.jd.bean;
//學(xué)生
public class Student {
    private Integer id;
    //課程分?jǐn)?shù)
    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;
    }
}
package com.jd.bean;
//課程分?jǐn)?shù)
public class Score {
    //分?jǐn)?shù)
    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;
    }
}

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • HashMap源碼中的位運(yùn)算符&詳解

    HashMap源碼中的位運(yùn)算符&詳解

    這篇文章主要介紹了HashMap源碼中的位運(yùn)算符&詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2020-07-07
  • rocketMQ如何避免消息重復(fù)消費(fèi)問(wèn)題

    rocketMQ如何避免消息重復(fù)消費(fèi)問(wèn)題

    這篇文章主要介紹了rocketMQ如何避免消息重復(fù)消費(fèi)問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-06-06
  • Spring控制Bean加載順序的操作方法

    Spring控制Bean加載順序的操作方法

    正常情況下,Spring 容器加載 Bean 的順序是不確定的,那么我們?nèi)绻枰错樞蚣虞d Bean 時(shí)應(yīng)如何操作?本文將詳細(xì)講述我們?nèi)绾尾拍芸刂?nbsp;Bean 的加載順序,需要的朋友可以參考下
    2024-05-05
  • SWT(JFace) 簡(jiǎn)易瀏覽器 制作實(shí)現(xiàn)代碼

    SWT(JFace) 簡(jiǎn)易瀏覽器 制作實(shí)現(xiàn)代碼

    SWT(JFace) 簡(jiǎn)易瀏覽器 制作實(shí)現(xiàn)代碼
    2009-06-06
  • 零基礎(chǔ)寫Java知乎爬蟲(chóng)之將抓取的內(nèi)容存儲(chǔ)到本地

    零基礎(chǔ)寫Java知乎爬蟲(chóng)之將抓取的內(nèi)容存儲(chǔ)到本地

    上一回我們說(shuō)到了如何把知乎的某些內(nèi)容爬取出來(lái),那么這一回我們就說(shuō)說(shuō)怎么把這些內(nèi)容存儲(chǔ)到本地吧。
    2014-11-11
  • 客戶端Socket與服務(wù)端ServerSocket串聯(lián)實(shí)現(xiàn)網(wǎng)絡(luò)通信

    客戶端Socket與服務(wù)端ServerSocket串聯(lián)實(shí)現(xiàn)網(wǎng)絡(luò)通信

    這篇文章主要為大家介紹了客戶端Socket與服務(wù)端ServerSocket串聯(lián)實(shí)現(xiàn)網(wǎng)絡(luò)通信的內(nèi)容詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助
    2022-03-03
  • JavaWeb會(huì)話技術(shù)詳解與案例

    JavaWeb會(huì)話技術(shù)詳解與案例

    會(huì)話技術(shù):在Web開(kāi)發(fā)中,服務(wù)器跟蹤用戶信息的奇數(shù)稱為會(huì)話技術(shù)。會(huì)話:指的是一個(gè)客戶端與服務(wù)器發(fā)生的一系列請(qǐng)求和響應(yīng)的過(guò)程。由于請(qǐng)求包含的信息,在請(qǐng)求被銷毀后也就不存在,多次讓用戶輸入賬號(hào)密碼,會(huì)影響用戶的使用體驗(yàn)感,基于此,產(chǎn)生了cookie和session技術(shù)
    2021-11-11
  • java實(shí)現(xiàn)的計(jì)算器功能示例【基于swing組件】

    java實(shí)現(xiàn)的計(jì)算器功能示例【基于swing組件】

    這篇文章主要介紹了java實(shí)現(xiàn)的計(jì)算器功能,結(jié)合實(shí)例形式分析了java基于swing組件實(shí)現(xiàn)計(jì)算器功能相關(guān)運(yùn)算操作技巧,需要的朋友可以參考下
    2017-12-12
  • 全面了解java異常

    全面了解java異常

    本文非常詳細(xì)的介紹了java異常,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們可以學(xué)習(xí)一下這篇文章
    2021-08-08
  • MyBatis-Ext快速入門實(shí)戰(zhàn)

    MyBatis-Ext快速入門實(shí)戰(zhàn)

    MyBatis-Ext是MyBatis的增強(qiáng)擴(kuò)展,和我們平常用的Mybatis-plus非常類似,本文主要介紹了MyBatis-Ext快速入門實(shí)戰(zhàn),感興趣的可以了解一下
    2021-10-10

最新評(píng)論