JAVA8之stream流式处理

傷城~ 2024-04-03 12:49 254阅读 0赞

1.筛选与切片(各个操作可以一起使用,对同一个流进行处理)

  • 说明

06e6b583862a4336a863e4ecd79130d3.jpeg

  • 测试代码:

    package test.java8.stream;

    import java.util.*;
    import java.util.stream.Collectors;
    import java.util.stream.Stream;

    /**

    • 筛选与切片
    • @author linaibo
    • @version 1.0
    • Create by 2022/8/7 19:45
      */

    public class Test1 {

    1. public static void main(String[] args){
    2. List<student> list = new ArrayList<student>();
    3. list.add(new student(1,"张三"));
    4. list.add(new student(1,"张三"));
    5. list.add(new student(3,"王五"));
    6. list.add(new student(3,"王五"));
    7. list.add(new student(5,"小七"));
    8. //filter
    9. List<student> list1 = list.stream().filter(s->(s.getId()>1)).filter(e->(e.getName().equals("王五"))).collect(Collectors.toList());
    10. list1.stream().forEach((s) ->{
    11. System.out.print(s.getId());
    12. System.out.println(s.getName());
    13. });
    14. System.out.println("filter11111111");
    15. //limit
    16. List<student> collect = list.stream().limit(2).collect(Collectors.toList());
    17. collect.forEach(item->{
    18. System.out.print(item.getId());
    19. System.out.println(item.getName());
    20. });
    21. System.out.println("limit11111111");
    22. //skip
    23. List<student> collect1 = list.stream().skip(3).collect(Collectors.toList());
    24. collect1.forEach(item->{
    25. System.out.print(item.getId());
    26. System.out.println(item.getName());
    27. });
    28. System.out.println("skip11111111");
    29. //distinct
    30. List<student> collect2 = list.stream().distinct().collect(Collectors.toList());
    31. collect2.forEach(item->{
    32. System.out.print(item.getId());
    33. System.out.println(item.getName());
    34. });
    35. }
    36. public static class student {
    37. private int id;
    38. private String name;
    39. public student(int id, String name) {
    40. this.id = id;
    41. this.name = name;
    42. }
    43. public int getId() {
    44. return id;
    45. }
    46. public void setId(int id) {
    47. this.id = id;
    48. }
    49. public String getName() {
    50. return name;
    51. }
    52. public void setName(String name) {
    53. this.name = name;
    54. }
    55. @Override
    56. public boolean equals(Object o) {
    57. if (this == o) return true;
    58. if (!(o instanceof student)) return false;
    59. student student = (student) o;
    60. return id == student.id && Objects.equals(name, student.name);
    61. }
    62. @Override
    63. public int hashCode() {
    64. return Objects.hash(id, name);
    65. }
    66. }

    }

  • 测试结果

    3王五
    3王五
    filter11111111
    1张三
    1张三
    limit11111111
    3王五
    5小七
    skip11111111
    1张三
    3王五
    5小七

2.映射

c65d23b82ab0424aa2cc70df333c9417.jpeg

  • 测试代码

    package test.java8.stream;

    import java.util.*;
    import java.util.stream.Collectors;
    import java.util.stream.Stream;

    /**

    • 映射
    • @author linaibo
    • @version 1.0
    • Create by 2022/10/15 15:15
      */

    public class Test2 {

    1. public static void main(String[] args) {
    2. List<Student> list = new ArrayList<Student>();
    3. list.add(new Student(1,"张三"));
    4. list.add(new Student(1,"张三"));
    5. list.add(new Student(3,"王五"));
    6. list.add(new Student(3,"王五"));
    7. list.add(new Student(5,"小七"));
    8. //map
    9. List<Integer> collect = list.stream().map(Student::getId).collect(Collectors.toList());
    10. collect.forEach(System.out::print);
    11. System.out.println(" map111111");
    12. //flatmap
    13. List<String> list2 = Arrays.asList("aaa","bbb","ccc");
    14. List<Object> collect1 = list2.stream().flatMap(Test2::filterCharter).collect(Collectors.toList());
    15. collect1.forEach(System.out::print);
    16. System.out.println(" flatMap111 11");
    17. }
    18. public static Stream<Character> filterCharter(String str){
    19. List<Character> list = new ArrayList<>();
    20. for(Character ch : str.toCharArray()){
    21. list.add(ch);
    22. }
    23. return list.stream();
    24. }
    25. public static class Student {
    26. private int id;
    27. private String name;
    28. public Student(int id, String name) {
    29. this.id = id;
    30. this.name = name;
    31. }
    32. public int getId() {
    33. return id;
    34. }
    35. public void setId(int id) {
    36. this.id = id;
    37. }
    38. public String getName() {
    39. return name;
    40. }
    41. public void setName(String name) {
    42. this.name = name;
    43. }
    44. }

    }

  • 测试结果

    11335 map111111
    aaabbbccc flatMap11111

    List collect = goodsRecordList.stream().map((goodsRecordTemp) -> {

    1. GoodsRecordVO goodsRecordVO = new GoodsRecordVO();
    2. BeanUtils.copyProperties(goodsRecordTemp, goodsRecordVO);
    3. goodsRecordVO.setCustomerName(codeToNameMap.get(goodsRecordTemp.getCustomerCode()));
    4. return goodsRecordVO;
    5. }).collect(Collectors.toList());
  1. map的用法也可以对进行两个bean之间的映射编辑处理,返回一个bean的集合,上述操作也可以使用for循环处理。

3.排序

  • 内容

souted()—自然排序(Comparable)

自然排序的对象必须实现compareble,按照compareto方法进行排序

sorted(Comparator com)—定制排序(Comparator)

比如student对象没有自然排序方式,只能用定制排序,根据对象中的某些项目进行定制排序

  • 测试代码

    package test.java8.stream;

    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    import java.util.Objects;
    import java.util.stream.Collectors;
    import java.util.stream.Stream;

    /**

    • @author linaibo
    • @version 1.0
    • Create by 2022/10/16 10:05
      */

    public class Test3 {

    1. public static void main(String[] args) {
    2. List<String> list1 = Arrays.asList("aaa", "eee", "ccc", "ddd");
    3. List<String> collect1 = list1.stream().sorted().collect(Collectors.toList());
    4. collect1.forEach(System.out::println);
    5. System.out.println("自然排序111111");
    6. List<Student> list = new ArrayList<Student>();
    7. list.add(new Student(1, 18, "张三"));
    8. list.add(new Student(5, 19, "张三"));
    9. list.add(new Student(9, 20, "王五"));
    10. list.add(new Student(8, 14, "王五"));
    11. list.add(new Student(1, 16, "小七"));
    12. List<Student> collect2 = list.stream()
    13. .sorted((e1, e2) -> {
    14. if (e1.getId() == e2.getId()) {
    15. return -(e1.getAge() - e2.getAge());
    16. } else {
    17. return -(e1.getId() - e2.getId());
    18. }
    19. })
    20. .collect(Collectors.toList());
    21. collect2.forEach(item -> {
    22. System.out.print(item.getId());
    23. System.out.print(item.getAge());
    24. System.out.println(item.getName());
    25. });
    26. System.out.println("定制排序111111");
    27. }
  1. public static class Student {
  2. private int id;
  3. private int age;
  4. private String name;
  5. public Student(int id, int age, String name) {
  6. this.id = id;
  7. this.age = age;
  8. this.name = name;
  9. }
  10. public int getId() {
  11. return id;
  12. }
  13. public void setId(int id) {
  14. this.id = id;
  15. }
  16. public int getAge() {
  17. return age;
  18. }
  19. public void setAge(int age) {
  20. this.age = age;
  21. }
  22. public String getName() {
  23. return name;
  24. }
  25. public void setName(String name) {
  26. this.name = name;
  27. }
  28. @Override
  29. public boolean equals(Object o) {
  30. if (this == o) return true;
  31. if (!(o instanceof Student)) return false;
  32. Student student = (Student) o;
  33. return id == student.id && age == student.age && Objects.equals(name, student.name);
  34. }
  35. @Override
  36. public int hashCode() {
  37. return Objects.hash(id, age, name);
  38. }
  39. }
  40. }
  • 测试结果

    aaa
    ccc
    ddd
    eee
    自然排序111111
    920王五
    814王五
    519张三
    118张三
    116小七
    定制排序111111

4.查找与匹配

allMatch—检查是否匹配所有元素

anyMatch—检查是否至少匹配一个元素

noneMatch—检查是否没有匹配所有元素

findFirst—返回第一个元素

findAny—返回当前流中的任意元素

count—返回流中元素的总个数

max—返回流中的最大值

min—返回流中的最小值

  1. package test.java8.stream;
  2. import java.util.*;
  3. /**
  4. * @author linaibo
  5. * @version 1.0
  6. * Create by 2022/10/16 10:46
  7. */
  8. public class Test4 {
  9. public static void main(String[] args) {
  10. List<Student> list = new ArrayList<Student>();
  11. list.add(new Student(1, 18, "张三"));
  12. list.add(new Student(5, 19, "张三"));
  13. list.add(new Student(9, 20, "王五"));
  14. list.add(new Student(8, 14, "王五"));
  15. list.add(new Student(1, 16, "小七"));
  16. //allMatch
  17. boolean allMatch = list.stream().allMatch(s -> s.getAge() == 18);
  18. System.out.println(allMatch);
  19. System.out.println("allMatch");
  20. //anyMatch
  21. boolean anyMatch = list.stream().anyMatch(s -> s.getAge() == 18);
  22. System.out.println(anyMatch);
  23. System.out.println("anyMatch");
  24. //noneMatch
  25. boolean noneMatch = list.stream().noneMatch(s -> s.getAge() == 18);
  26. System.out.println(noneMatch);
  27. System.out.println("noneMatch");
  28. //findFirst
  29. Optional<Student> first = list.stream().findFirst();
  30. Student student = first.get();
  31. System.out.print(student.getId());
  32. System.out.print(student.getAge());
  33. System.out.print(student.getName());
  34. System.out.println("findFirst");
  35. //findAny
  36. Optional<Student> any = list.stream().findAny();
  37. Student student1 = any.get();
  38. System.out.print(student1.getId());
  39. System.out.print(student1.getAge());
  40. System.out.print(student1.getName());
  41. System.out.println("findAny");
  42. //count
  43. long count = list.stream().count();
  44. System.out.println(count);
  45. System.out.println("count");
  46. //max
  47. Optional<Student> max = list.stream().max(Comparator.comparingInt(Student::getAge));
  48. Student student2 = max.get();
  49. System.out.print(student2.getId());
  50. System.out.print(student2.getAge());
  51. System.out.print(student2.getName());
  52. System.out.println("max");
  53. //min
  54. Optional<Student> min = list.stream().min(Comparator.comparingInt(Student::getAge));
  55. Student student3 = min.get();
  56. System.out.print(student3.getId());
  57. System.out.print(student3.getAge());
  58. System.out.print(student3.getName());
  59. System.out.println("min");
  60. }
  61. public static class Student {
  62. private int id;
  63. private int age;
  64. private String name;
  65. public Student(int id, int age, String name) {
  66. this.id = id;
  67. this.age = age;
  68. this.name = name;
  69. }
  70. public int getId() {
  71. return id;
  72. }
  73. public void setId(int id) {
  74. this.id = id;
  75. }
  76. public int getAge() {
  77. return age;
  78. }
  79. public void setAge(int age) {
  80. this.age = age;
  81. }
  82. public String getName() {
  83. return name;
  84. }
  85. public void setName(String name) {
  86. this.name = name;
  87. }
  88. @Override
  89. public boolean equals(Object o) {
  90. if (this == o) return true;
  91. if (!(o instanceof Student)) return false;
  92. Student student = (Student) o;
  93. return id == student.id && age == student.age && Objects.equals(name, student.name);
  94. }
  95. @Override
  96. public int hashCode() {
  97. return Objects.hash(id, age, name);
  98. }
  99. }
  100. }
  • 测试结果

    false
    allMatch
    true
    anyMatch
    false
    noneMatch
    118张三findFirst
    118张三findAny
    5
    count
    920王五max
    814王五min

5.归约

reduce—将流中元素反复结合起来,最后得到一个值

2f7bfe7db86f4cda82d027221648afd0.jpeg

  • 测试代码

    package test.java8.stream;

    import java.util.ArrayList;
    import java.util.List;
    import java.util.Objects;
    import java.util.Optional;

    /**

    • @author linaibo
    • @version 1.0
    • Create by 2022/10/16 11:09
      */

    public class Test5 {

    1. public static void main(String[] args) {
    2. List<Student> list = new ArrayList<Student>();
    3. list.add(new Student(1, 18, "张三"));
    4. list.add(new Student(5, 19, "张三"));
    5. list.add(new Student(9, 20, "王五"));
    6. list.add(new Student(8, 14, "王五"));
    7. list.add(new Student(1, 16, "小七"));
    8. //reduce
    9. Integer reduce = list.stream().map(Student::getAge).reduce(0, (x, y) -> x + y);
    10. System.out.println(reduce);
    11. System.out.println("reduce");
    12. //reduce
    13. Optional<Integer> reduce1 = list.stream().map(Student::getAge).reduce((x, y) -> x + y);
    14. System.out.println(reduce1.get());
    15. System.out.println("reduce");
    16. }
    17. public static class Student {
    18. private int id;
    19. private int age;
    20. private String name;
    21. public Student(int id, int age, String name) {
    22. this.id = id;
    23. this.age = age;
    24. this.name = name;
    25. }
    26. public int getId() {
    27. return id;
    28. }
    29. public void setId(int id) {
    30. this.id = id;
    31. }
    32. public int getAge() {
    33. return age;
    34. }
    35. public void setAge(int age) {
    36. this.age = age;
    37. }
    38. public String getName() {
    39. return name;
    40. }
    41. public void setName(String name) {
    42. this.name = name;
    43. }
    44. @Override
    45. public boolean equals(Object o) {
    46. if (this == o) return true;
    47. if (!(o instanceof Student)) return false;
    48. Student student = (Student) o;
    49. return id == student.id && age == student.age && Objects.equals(name, student.name);
    50. }
    51. @Override
    52. public int hashCode() {
    53. return Objects.hash(id, age, name);
    54. }
    55. }

    }

  • 测试结果

    87
    reduce
    87
    reduce

6.归集

  • 测试代码

    package test.java8.stream;

    import java.util.*;
    import java.util.function.BinaryOperator;
    import java.util.stream.Collector;
    import java.util.stream.Collectors;

    /**

    • @author linaibo
    • @version 1.0
    • Create by 2022/10/16 11:09
      */

    public class Test6 {

    1. public static void main(String[] args) {
    2. List<Student> list = new ArrayList<Student>();
    3. list.add(new Student(1, 18, "张三"));
    4. list.add(new Student(5, 19, "张三"));
    5. list.add(new Student(9, 20, "王五"));
    6. list.add(new Student(8, 14, "王五"));
    7. list.add(new Student(1, 16, "小七"));
    8. //toList
    9. List<Student> collect = list.stream().filter(s -> s.getAge() == 18).collect(Collectors.toList());
    10. collect.forEach(item->{
    11. System.out.print(item.getId());
    12. System.out.print(item.getAge());
    13. System.out.println(item.getName());
    14. });
    15. System.out.println("toList");
    16. //toSet
    17. Set<Student> collect1 = list.stream().filter(s -> s.getAge() == 19).collect(Collectors.toSet());
    18. collect1.forEach(item->{
    19. System.out.print(item.getId());
    20. System.out.print(item.getName());
    21. System.out.println(item.getAge());
    22. });
    23. System.out.println("toSet");
    24. //toMap
    25. Map<Integer, String> collect2 = list.stream().filter(s -> s.getAge() > 15).collect(Collectors.toMap(Student::getId, Student::getName,(v1,v2)->v1));
    26. collect2.forEach((k,v)->{
    27. System.out.print(k);
    28. System.out.println(v);
    29. });
    30. System.out.println("toMap1");
    31. Map<Integer, Student> collect3 = list.stream().filter(s -> s.getAge() > 15).collect(Collectors.toMap(Student::getId, s -> s,(v1,v2)->v2));
    32. collect3.forEach((k,v)->{
    33. System.out.print(k);
    34. System.out.println(v.getName());
    35. });
    36. System.out.println("toMap2");
    37. //count
    38. Long collect5 = list.stream().filter(s -> s.getAge() > 18).collect(Collectors.counting());
    39. System.out.println(collect5);
    40. System.out.println("count");
    41. //summingInt
    42. Integer collect4 = list.stream().filter(s -> s.getAge() > 18).collect(Collectors.summingInt(Student::getAge));
    43. System.out.println(collect4);
    44. System.out.println("summingInt");
    45. //averagingInt
    46. Double collect7 = list.stream().filter(s -> s.getAge() > 18).collect(Collectors.averagingInt(Student::getAge));
    47. System.out.println(collect7);
    48. System.out.println("averagingInt");
    49. //groupingBy 可以多级分组
    50. Map<Integer, List<Student>> collect6 = list.stream().filter(s -> s.getAge() > 18).collect(Collectors.groupingBy(Student::getId));
    51. collect6.forEach((k,v)->{
    52. System.out.println(k);
    53. System.out.println(v.size());
    54. });
    55. System.out.println("groupingBy");
    56. //maxBy
    57. Optional<Student> collect8 = list.stream().collect(Collectors.maxBy(Comparator.comparingInt(Student::getAge)));
    58. Student student = collect8.get();
    59. System.out.print(student.getId());
    60. System.out.println(student.getName());
    61. System.out.println("maxBy");
    62. //minBy
    63. Optional<Student> collect9 = list.stream().collect(Collectors.minBy(Comparator.comparingInt(Student::getAge)));
    64. Student student2 = collect9.get();
    65. System.out.print(student2.getId());
    66. System.out.println(student2.getName());
    67. System.out.println("minBy");
    68. //partitioningBy
    69. Map<Boolean, List<Student>> collect10 = list.stream().collect(Collectors.partitioningBy(s -> s.getAge() > 18));
    70. collect10.forEach((k,v)->{
    71. System.out.println(k);
    72. System.out.println(v.size());
    73. });
    74. System.out.println("partitioningBy");
    75. //groupingBy AND reducing
    76. Map<Integer, Optional<Student>> collect11 = list.stream().collect(Collectors.groupingBy(Student::getId, Collectors.reducing(BinaryOperator.maxBy(Comparator.comparingInt(Student::getAge)))));
    77. collect11.forEach((k,v)->{
    78. System.out.println(k);
    79. System.out.println(v.get().getAge());
    80. });
    81. System.out.println("groupingBy AND reducing");
    82. }
    83. public static class Student {
    84. private int id;
    85. private int age;
    86. private String name;
    87. public Student(int id, int age, String name) {
    88. this.id = id;
    89. this.age = age;
    90. this.name = name;
    91. }
    92. public int getId() {
    93. return id;
    94. }
    95. public void setId(int id) {
    96. this.id = id;
    97. }
    98. public int getAge() {
    99. return age;
    100. }
    101. public void setAge(int age) {
    102. this.age = age;
    103. }
    104. public String getName() {
    105. return name;
    106. }
    107. public void setName(String name) {
    108. this.name = name;
    109. }
    110. @Override
    111. public boolean equals(Object o) {
    112. if (this == o) return true;
    113. if (!(o instanceof Student)) return false;
    114. Student student = (Student) o;
    115. return id == student.id && age == student.age && Objects.equals(name, student.name);
    116. }
    117. @Override
    118. public int hashCode() {
    119. return Objects.hash(id, age, name);
    120. }
    121. }

    }

  • 测试结果

    118张三
    toList
    5张三19
    toSet
    1张三
    5张三
    9王五
    toMap1
    1小七
    5张三
    9王五
    toMap2
    2
    count
    39
    summingInt
    19.5
    averagingInt
    5
    1
    9
    1
    groupingBy
    9王五
    maxBy
    8王五
    minBy
    false
    3
    true
    2
    partitioningBy
    1
    18
    5
    19
    8
    14
    9
    20
    groupingBy AND reducing

分组求和

  1. Map<String, Integer> materInfoMap = list
  2. .stream()
  3. .filter(item -> item.getMaterialCode() != null)
  4. .collect(groupingBy(Goods::getMaterialCode, reducing(0, Goods::getMaterialQty, Integer::sum)));
  5. materInfoMap.forEach((key,value)->{
  6. System.out.println(key + value);
  7. });

发表评论

表情:
评论列表 (有 0 条评论,254人围观)

还没有评论,来说两句吧...

相关阅读