代码
package com.jianshu;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* stream 对象分组
*
* @author archer
* @since 2022/12/28 8:51
*/
public class StreamGroup {
public static void main(String[] args) {
List<Person> personList = new ArrayList<>();
Person person1 = new Person(1, "张三");
Person person2 = new Person(0, "李四");
Person person3 = new Person(1, "王五");
Person person4 = new Person(1, "马六");
personList.add(person1);
personList.add(person2);
personList.add(person3);
personList.add(person4);
List<Integer> sexes = personList.stream().map(Person::getSex).collect(Collectors.toList());
System.out.println("全部值:");
sexes.forEach(System.out::println);
sexes = personList.stream().map(Person::getSex).distinct().collect(Collectors.toList());
System.out.println("去重后的值:");
sexes.forEach(System.out::println);
}
@Data
private static class Person {
/**
* 初始化对象
*
* @param sex 性别
* @param name 姓名
*/
public Person(Integer sex, String name) {
this.sex = sex;
this.name = name;
}
/**
* 性别
*/
private Integer sex;
/**
* 姓名
*/
private String name;
}
}
输出结果
全部值:
1
0
1
1
去重后的值:
1
0