import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Filter {
public static void main(String[] args) {
List<String> lines = Arrays.asList("spring", "node", "mkyong","mkyong");
System.out.println(lines);
//从集合中获得元素
String item = lines.stream().filter(line-> "mkyong".equals(line)).findAny().orElse(null);
System.out.println(item);
//从集合中获取集合
List<String> list = lines.stream().filter(line-> !"mkyong".equals(line)).collect(Collectors.toList());
list.forEach(System.out::println);
//从对象类中获得元素
class Person{
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Person(String name, Integer age) {
super();
this.name = name;
this.age = age;
}
}
List<Person> persons = Arrays.asList(new Person("mkyong", 20),new Person("michael", 21), new Person("lawrence", 23));
Integer age = persons.stream().filter(x -> "michael".equals(x.getName())).map(Person::getAge).findAny().orElse(Integer.valueOf(0));
System.out.println(age);
}
}
import java.util.List;
import java.util.stream.Collectors;
public class Filter {
public static void main(String[] args) {
List<String> lines = Arrays.asList("spring", "node", "mkyong","mkyong");
System.out.println(lines);
//从集合中获得元素
String item = lines.stream().filter(line-> "mkyong".equals(line)).findAny().orElse(null);
System.out.println(item);
//从集合中获取集合
List<String> list = lines.stream().filter(line-> !"mkyong".equals(line)).collect(Collectors.toList());
list.forEach(System.out::println);
//从对象类中获得元素
class Person{
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Person(String name, Integer age) {
super();
this.name = name;
this.age = age;
}
}
List<Person> persons = Arrays.asList(new Person("mkyong", 20),new Person("michael", 21), new Person("lawrence", 23));
Integer age = persons.stream().filter(x -> "michael".equals(x.getName())).map(Person::getAge).findAny().orElse(Integer.valueOf(0));
System.out.println(age);
}
}