image.pnghttps://baijiahao.baidu.com/s?id=1711922146914662710&wfr=spider&for=pc

stream

https://blog.csdn.net/q1532440739/article/details/113864280

filter()和collect()

在Java 8中,stream.filter()过滤List列表,collect()将流转换为List列表

  1. import java.util.Arrays;
  2. import java.util.List;
  3. import java.util.stream.Collectors;
  4. public class NowJava8 {
  5. public static void main(String[] args) {
  6. List<String> lines = Arrays.asList("spring", "node", "mkyong");
  7. List<String> result = lines.stream() // convert list to stream
  8. .filter(line -> !"mkyong".equals(line)) // we dont like mkyong
  9. .collect(Collectors.toList()); // collect the output and convert streams to a List
  10. result.forEach(System.out::println); //output : spring, node
  11. }
  12. }
  13. // output
  14. spring
  15. node

filter()、findAny()和orElse()

在java8中,stream.filter()过滤List列表,findAny()、orElse(null)返回满足条件的对象

  1. public class Person {
  2. private String name;
  3. private int age;
  4. public Person(String name, int age) {
  5. this.name = name;
  6. this.age = age;
  7. }
  8. //gettersm setters, toString
  9. }
  1. import java.util.Arrays;
  2. import java.util.List;
  3. public class NowJava8 {
  4. public static void main(String[] args) {
  5. List<Person> persons = Arrays.asList(
  6. new Person("mkyong", 30),
  7. new Person("jack", 20),
  8. new Person("lawrence", 40)
  9. );
  10. Person result1 = persons.stream() // Convert to steam
  11. .filter(x -> "jack".equals(x.getName())) // we want "jack" only
  12. .findAny() // If 'findAny' then return found
  13. .orElse(null); // If not found, return null
  14. System.out.println(result1);
  15. Person result2 = persons.stream()
  16. .filter(x -> "ahmook".equals(x.getName()))
  17. .findAny()
  18. .orElse(null);
  19. System.out.println(result2);
  20. }
  21. }
  22. // output
  23. Person{name='jack', age=20}
  24. null

filter()和map()

  1. import java.util.Arrays;
  2. import java.util.List;
  3. import java.util.stream.Collectors;
  4. public class NowJava8 {
  5. public static void main(String[] args) {
  6. List<Person> persons = Arrays.asList(
  7. new Person("mkyong", 30),
  8. new Person("jack", 20),
  9. new Person("lawrence", 40)
  10. );
  11. String name = persons.stream()
  12. .filter(x -> "jack".equals(x.getName()))
  13. .map(Person::getName) //convert stream to String
  14. .findAny()
  15. .orElse("");
  16. System.out.println("name : " + name);
  17. List<String> collect = persons.stream()
  18. .map(Person::getName)
  19. .collect(Collectors.toList());
  20. collect.forEach(System.out::println);
  21. }
  22. }
  23. //output
  24. name : jack
  25. mkyong
  26. jack
  27. lawrence