JAva 8 stream listツール
2545 ワード
1.listソート
//テストセットオブジェクトpublic class Student{private String name;private String sex;private double height;private double weight;private int;Student(){}Student(String name,String sex,double height,double weight,int){this.name=name;this.sex=sex;this.height=height;this.weight=weight;this.age=age;}
public static void main(String[] args) {
List studentList = Lists.newArrayList();
studentList.add(new Student(" 3"," ",50,50,50));
//
for(int i = 0;i<10;i++){
studentList.add(new Student(" "+i," "+i,i+1,i+2,i+3));
}
// -
studentList.sort(Comparator.comparing(Student::getAge,(x,y)->{
if(x>y){
return 1;
}else if(x==y){
return 0;
}else{
return -1;
}
}));
// -
studentList.sort(Comparator.comparing(Student::getAge,(x,y)->{
if(x>y){
return 1;
}else if(x==y){
return 0;
}else{
return -1;
}
}).reversed());
// -
studentList.sort(Comparator.comparing(Student::getAge).thenComparing(Student::getHeight));
studentList.forEach(student ->{
System.out.println(student.getName()+":"+student.getAge());
});
}
2.list抽出属性は新しいListまたはMapを生産する
public static void main(String[]args){List studentList=Lists.newArrayList();studentList.add(new Student(「王君3」,「男」,50,3,3));//データソースfor(int i=0;i<10;i+){studentList.add(new Student(「明」+i,「男」+i,i+1,i+2,i+3));}抽出対象属性は、新たなリストリストリストリスト=studentListとなる.stream().map(Student::getAge).collect(Collectors.toList());//抽出対象属性はmap Map 1=studentListとなる.stream().collect(Collectors.toMap(Student::getAge,a->a,(k1,k2)->k1)); Map map2 = studentList.stream().collect(Collectors.toMap(Student::getAge,Student::getName,(k1,k2)->k1)); }
3.listフィルタ、グループ化
public static void main(String[] args) {
List studentList = Lists.newArrayList();
studentList.add(new Student(" 3"," ",50,3,3));
//
for(int i = 0;i<10;i++){
studentList.add(new Student(" "+i," "+i,i+1,i+2,i+3));
}
//
List lsit = studentList.stream().filter(student-> student.getAge()>6).collect(Collectors.toList());
//
Map> map = studentList.stream().collect(Collectors.groupingBy(Student::getAge));
}