Java8使⽤stream().map()提取List对象的某⼀列值及排重List对象类(StudentInfo)
public class StudentInfo implements Comparable<StudentInfo> {
//名称
private String name;
//性别 true男 false⼥
private Boolean gender;
//年龄
private Integer age;
//⾝⾼
private Double height;
//出⽣⽇期
private LocalDate birthday;
public StudentInfo(String name, Boolean gender, Integer age, Double height, LocalDate birthday){
this.name = name;
this.age = age;
this.height = height;
this.birthday = birthday;
}
public String toString(){
String info = String.format("%s\t\t%s\t\t%s\t\t\t%s\t\t%s",this.String(),String(),String(),String());
return info;
}
public static void printStudents(List<StudentInfo> studentInfos){
System.out.println("[姓名]\t\t[性别]\t\t[年龄]\t\t[⾝⾼]\t\t[⽣⽇]");
System.out.println("----------------------------------------------------------");
studentInfos.forEach(s->System.out.String()));
System.out.println(" ");
}
@Override
public int compareTo(StudentInfo ob) {
return this.Age());
//return 1;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Boolean getGender() {
return gender;
}
public void setGender(Boolean gender) {
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Double getHeight() {
return height;
}
public void setHeight(Double height) {
this.height = height;
}
public LocalDate getBirthday() {
return birthday;
}
public void setBirthday(LocalDate birthday) {
this.birthday = birthday;
}
}
StudentInfo对象类
测试数据
//测试数据,请不要纠结数据的严谨性
List<StudentInfo> studentList = new ArrayList<>();
studentList.add(new StudentInfo("李⼩明",true,18,1.76,LocalDate.of(2001,3,23)));
studentList.add(new StudentInfo("张⼩丽",false,18,1.61,LocalDate.of(2001,6,3)));
studentList.add(new StudentInfo("王⼤朋",true,19,1.82,LocalDate.of(2000,3,11)));
studentList.add(new StudentInfo("陈⼩跑",false,17,1.67,LocalDate.of(2002,10,18)));
提取某⼀列(以name为例)
//输出List
StudentInfo.printStudents(studentList);
//从对象列表中提取⼀列(以name为例)
java stream
List<String> nameList = studentList.stream().map(StudentInfo::getName).List());//提取后输出name nameList.forEach(s-> System.out.println(s));
输出结果如下图:
提取age列并排重(使⽤distinct()函数)
//提取前输出
StudentInfo.printStudents(studentList);
//从对象列表中提取age并排重
List<Integer> ageList = studentList.stream().map(StudentInfo::getAge).distinct().List());
ageList.forEach(a-> System.out.println(a));
结果如下图:
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论