public class Test {
public static void main(String[] args) {
ArrayList<Person> temp = new ArrayList<>();
List<Person> personList = init();
//filter 筛选器
//1.筛选出personList中工资大于8000的人 并存入新List
List<Person> collect = personList.stream()
.filter(person -> person.getSalary() > 8000).collect(Collectors.toList());
//2.筛选输出personList中性别为男的person
personList.stream()
.filter(person -> person.getSex().equals("male"))
.forEach(person -> System.out.println(person));
System.out.println("=========================================");
//map 对集合中的对象的做统一操作
//1.给集合中的Person每人加1000元工资 并输出集合中的每个Person
personList.stream()
.map(person -> {
person.setSalary(person.getSalary() + 1000);
//注意返回值是下方forEach遍历的内容
return person;
})
.forEach(person-> System.out.println(person));
System.out.println("=========================================");
//limit 取集合中前n个元素
personList.stream().limit(3).forEach(person -> System.out.println(person));
System.out.println("=========================================");
//sorted 排序
//reduce 用于统计集合中的值
}
//初始化PersonList
static List<Person> init() {
List<Person> personList = Arrays.asList(
new Person("Tom", 8900, "male", "New York"),
new Person("Jack", 7000, "male", "Washington"),
new Person("Lily", 7800, "female", "Washington"),
new Person("Anni", 8200, "female", "New York"),
new Person("Owen", 9500, "male", "New York"),
new Person("Alisa", 7900, "female", "New York")
);
return personList;
}
}
class Person {
private String name; // 姓名
private int salary; // 薪资
private int age; // 年龄
private String sex; //性别
private String area; // 地区
// 构造方法
public Person(String name, int salary, String sex, String area) {
this.name = name;
this.salary = salary;
this.sex = sex;
this.area = area;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getArea() {
return area;
}
public void setArea(String area) {
this.area = area;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", salary=" + salary +
", age=" + age +
", sex='" + sex + '\'' +
", area='" + area + '\'' +
'}';
}
}
纸上得来终觉浅,绝知此事须躬行