首先讲一下Comparable接口和Comparator接口,以及他们之间的差异。有助于Collections.sort()方法的使用。请参考
1.Comparable自然规则排序
//在自定义类Student里面实现Comparable接口,并重写抽象方法compareTo(Student o);
//Collections.sort(集合);
先看一个简单的例子:
public static void main(String[] args) {
List<Integer> nums = new ArrayList<Integer>();
nums.add(3);
nums.add(5);
nums.add(1);
nums.add(0);
System.out.println(nums);
Collections.sort(nums);
System.out.println(nums);
}
输出结果:
[3, 5, 1, 0]
[0, 1, 3, 5]
2.Comparator专门规则排序(l临时排序)
//新建一个实现了Comparator接口的类,并重写抽象方法compare(Student o1, Student o2);
//Collections.sort(集合,实现了Comparator接口的类的实例化对象);
st<Students> students = new ArrayList<Students>();
students.add(new Students(23, 100));
students.add(new Students(27, 98));
students.add(new Students(29, 99));
students.add(new Students(29, 98));
students.add(new Students(22, 89));
Collections.sort(students, new Comparator<Students>() {
@Override
public int compare(Students o1, Students o2) {
int i = o1.getScore() - o2.getScore();
if(i == 0){
return o1.getAge() - o2.getAge();
}
return i;
}
});
for(Students stu : students){
System.out.println("score:" + stu.getScore() + ":age" + stu.getAge());
}
二:集合提取
1.利用Google的 import com.google.common.collect.Lists;
代码:
public void listToList(){
//源list
List<Result> listResults = Lists.newArrayList(new Result(1,"test1"),new Result(2,"test2"),new Result(3,"test3"));
//转换为目标list
List<String> strLists = Lists.transform(listResults,new Function<Result,String>(){
@Override
public String apply(Result result){
return result.getNameStr();
}
});
}
2.lamada表达式
要提取属性的话,用Stream中的map,然后使用方法引用,就可以了。
举个例子Student类中有name属性:
List<Student> students = new ArrayList<Student>();
List<String> names =students.stream().map(Student::getName).collect(Collectors.toList());
-
集合 转化为 集合
List students = persons.stream().map(person -> {
Student student = new Student();
BeanUtils.copyProperties(person, student);
if (person.getName() == “张三”) {
student.setSchoolName(“三中”);
student.setsId(3L);
}
if (person.getName() == “李四”) {
student.setSchoolName(“四中”);
student.setsId(4L);
}
return student;
}).collect(Collectors.toList());
System.out.println("students = " + students);}