【JAVA8】stream操做将列表中实体List的某个属性Set单独拿出来

public static void main(String[] args) {
            List<Stu> stuList = new ArrayList<>();
            stuList.add(new Stu("张三", 3));
            stuList.add(new Stu("李四", 4));
            Set<String> nameSet = stuList.stream().collect(HashSet::new,
            (s, stu) -> { s.add( stu.name ); }, (s1, s2) ->{ s1.addAll(s2); });
            System.out.println(nameSet);
    }

static class Stu{
    String name;
    int age;
    Stu(String name, int age){
        this.name = name;
        this.age = age;
    }
}

    打印结果:[李四, 张三]

    collect参数介绍:
/**
 * @param <R> 返回容器类型
 * @param supplier 返回容器的构造方法
 * @param accumulator 容器添加方法
 * @param combiner 容器的合并方法
 */
<R> R collect(Supplier<R> supplier,
              BiConsumer<R, ? super T> accumulator,
              BiConsumer<R, R> combiner);
相关文章
相关标签/搜索