package com.ken.test;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class TestJava8List {
public static void main(String[] args) {
User user1 = new User(21,”张三”);
User user2 = new User(25,”李四”);
User user3 = new User(22,”王五”);
User user4 = new User(19,”赵柳”);
List<User> list = new ArrayList<User>();
list.add(user1);
list.add(user2);
list.add(user3);
list.add(user4);
for(User u :list){
System.out.println(u);
}
List<User> newList = list.stream().sorted(Comparator.comparing(User::getAge))
.collect(Collectors.toList());
for(User u :newList){
System.out.println(u);
}
}
}
class User {
private int age;
private String name;
public User(int i, String s) {
this.age = i;
this.name = s;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return “User [age=” + age + “, name=” + name + “]”;
}
}
运行结果:
User [age=21, name=张三]
User [age=25, name=李四]
User [age=22, name=王五]
User [age=19, name=赵柳]
User [age=19, name=赵柳]
User [age=21, name=张三]
User [age=22, name=王五]
User [age=25, name=李四]