stream的用法

/**
 * 筛选出Integer集合中大于7的元素,并打印出来
 */
private static void test2() {
    List<Integer> list = Arrays.asList(6, 7, 3, 8, 1, 2, 9);
    Stream<Integer> stream1 = list.stream();
    stream1.filter(x -> x > 7).forEach(System.out::println);

}

/**
 * 筛选员工中工资高于8000的人,并形成新的集合。 形成新集合依赖collect(收集),后文有详细介绍。
 */
private static void test4() {
    List<Person> personList = new ArrayList<Person>();
    personList.add(new Person("Tom", 8900, 23, "male", "New York"));
    personList.add(new Person("Jack", 7000, 25, "male", "Washington"));
    personList.add(new Person("Lily", 7800, 21, "female", "Washington"));
    personList.add(new Person("Anni", 8200, 24, "female", "New York"));
    personList.add(new Person("Owen", 9500, 25, "male", "New York"));
    personList.add(new Person("Alisa", 7900, 26, "female", "New York"));
    List<String> fiterList = personList.stream().filter(x -> x.getSalary() > 8000).map(Person::getName)
            .collect(Collectors.toList());
    System.out.print("高于8000的员工姓名:" + fiterList);
}
posted on 2024-08-09 09:57  坐在云上飘  阅读(40)  评论(0)    收藏  举报