大部分都是用lambda实现的,在jdk为1.8时才能生效
排序
public class Person {
private String name;
private int age;
public Person(String name, int age) {
setAge(age);
setName(name);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
import java.util.ArrayList;
import java.util.List;
public class ListSort{
public static void main(String[] args) {
Person p1 = new Person("Jack", 12);
Person p2 = new Person("Nick", 11);
Person p3 = new Person("Bob", 14);
Person p4 = new Person("Lucy", 18);
List<Person> sortList = new ArrayList<Person>();
sortList.add(p1);
sortList.add(p2);
sortList.add(p3);
sortList.add(p4);
//顺序
sortList.sort((a, b) -> a.getAge() - b.getAge());
//倒序
//sortList.sort((a, b) -> b.getAge() - a.getAge());
sortList.forEach(p -> System.out.print(p.getName() + ":" + p.getAge() + '\n'));
}
}
打印结果:
Nick:11
Jack:12
Bob:14
Lucy:18
筛选
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class ListFilter {
public static void main(String[] args) {
Person p1 = new Person("Jack", 12);
Person p2 = new Person("Nick", 11);
Person p3 = new Person("Bob", 14);
Person p4 = new Person("Lucy", 18);
List<Person> filterList = new ArrayList<Person>();
filterList.add(p1);
filterList.add(p2);
filterList.add(p3);
filterList.add(p4);
List<Person> ageFilter = filterList.stream().filter(p -> p.getAge() > 13).collect(Collectors.toList());
List<Person> nameFilter = filterList.stream().filter(p -> p.getName().equals("Jack")).collect(Collectors.toList());
System.out.println("ageFilter:");
ageFilter.forEach(p -> System.out.print(p.getName() + ":" + p.getAge() + '\n'));
System.out.println("nameFilter:");
nameFilter.forEach(p -> System.out.print(p.getName() + ":" + p.getAge() + '\n'));
}
}
输出:
ageFilter:
Bob:14
Lucy:18
nameFilter:
Jack:12
截取
import java.util.ArrayList;
import java.util.List;
public class ListSubList {
public static void main(String[] args) {
Person p1 = new Person("Jack", 12);
Person p2 = new Person("Nick", 11);
Person p3 = new Person("Bob", 14);
Person p4 = new Person("Lucy", 18);
List<Person> subList = new ArrayList<Person>();
subList.add(p1);
subList.add(p2);
subList.add(p3);
subList.add(p4);
//subList(indexStart, indexEnd);indexStart开始位置,包含。indexEnd结束位置,不包含
subList = subList.subList(1, 4);
subList.forEach(p -> System.out.print(p.getName() + ":" + p.getAge() + '\n'));
}
}
输出
Nick:11
Bob:14
Lucy:18
分组
public class ListSubList {
public static void main(String[] args) {
Person p1 = new Person("Jack", 12);
Person p2 = new Person("Bob", 11);
Person p3 = new Person("Bob", 14);
Person p4 = new Person("Lucy", 18);
List<Person> persons = new ArrayList<Person>();
subList.add(p1);
subList.add(p2);
subList.add(p3);
subList.add(p4);
Map<String, List<Person>> personsMap = persons .stream().collect(Collectors.groupingBy(person-> person.getName()));
}
}