https://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列表
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class NowJava8 {
public static void main(String[] args) {
List<String> lines = Arrays.asList("spring", "node", "mkyong");
List<String> result = lines.stream() // convert list to stream
.filter(line -> !"mkyong".equals(line)) // we dont like mkyong
.collect(Collectors.toList()); // collect the output and convert streams to a List
result.forEach(System.out::println); //output : spring, node
}
}
// output
spring
node
filter()、findAny()和orElse()
在java8中,stream.filter()过滤List列表,findAny()、orElse(null)返回满足条件的对象
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
//gettersm setters, toString
}
import java.util.Arrays;
import java.util.List;
public class NowJava8 {
public static void main(String[] args) {
List<Person> persons = Arrays.asList(
new Person("mkyong", 30),
new Person("jack", 20),
new Person("lawrence", 40)
);
Person result1 = persons.stream() // Convert to steam
.filter(x -> "jack".equals(x.getName())) // we want "jack" only
.findAny() // If 'findAny' then return found
.orElse(null); // If not found, return null
System.out.println(result1);
Person result2 = persons.stream()
.filter(x -> "ahmook".equals(x.getName()))
.findAny()
.orElse(null);
System.out.println(result2);
}
}
// output
Person{name='jack', age=20}
null
filter()和map()
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class NowJava8 {
public static void main(String[] args) {
List<Person> persons = Arrays.asList(
new Person("mkyong", 30),
new Person("jack", 20),
new Person("lawrence", 40)
);
String name = persons.stream()
.filter(x -> "jack".equals(x.getName()))
.map(Person::getName) //convert stream to String
.findAny()
.orElse("");
System.out.println("name : " + name);
List<String> collect = persons.stream()
.map(Person::getName)
.collect(Collectors.toList());
collect.forEach(System.out::println);
}
}
//output
name : jack
mkyong
jack
lawrence