1.获取实体内某个元素放入list集合中
List<String> ids = caseinfos.parallelStream().map(Caseinfo::getId).collect(Collectors.toList());
List<String> ids = caseinfos.parallelStream().map(a -> a.getId()).collect(Collectors.toList());
2.list排序
List<String> myList = Arrays.asList("a1", "a2", "b1", "c2", "c1");
myList.sort((a, b) -> b.compareTo(a));
myList.sort(Comparator.reverseOrder());
[c2, c1, b1, a2, a1]
3.字符串变大写并排序
stringCollection.stream().map(String::toUpperCase).sorted((a, b) -> b.compareTo(a)).forEach(System.out::println);
4.验证 list 中 string 是否有以 a 开头的, 匹配到第一个,即返回 true
boolean anyStartsWithA =
stringCollection.stream().anyMatch((s) -> s.startsWith("a"));
5.验证 list 中 string 是否都是以 a 开头的
boolean allStartsWithA =
stringCollection.stream().allMatch((s) -> s.startsWith("a"));
6.验证 list 中 string 是否都不是以 z 开头的
boolean noneStartsWithZ =
stringCollection.stream().noneMatch((s) -> s.startsWith("z"));
7.验证 list 中 string 以 b 开头的元素数量
long startsWithB =
stringCollection.stream().filter((s) -> s.startsWith("b")).count();
8.排序
List<String> myList = Arrays.asList("a1", "a2", "b1", "c2", "c1");
myList.stream()
.filter(s -> s.startsWith("c"))
.map(String::toUpperCase)
.sorted(Comparator.naturalOrder())
.forEach(System.out::println);
int[] arr = {1, 5, 9, 7, 2, 3, 7, -1, 0, 3};
arr = IntStream.of(arr).boxed().sorted(Comparator.reverseOrder()).mapToInt(Integer::intValue).toArray();
System.out.println(Arrays.toString(arr));
C1
C2
[9, 7, 7, 5, 3, 3, 2, 1, 0, -1]
9.list转Map
- (k1, k2) -> k2表示key相等时,新的值会覆盖旧的值
Map<String, String> deptMap = departments.parallelStream()
.collect(Collectors.toMap(Department::getGridNo, Department::getDeptCode, (k1, k2) -> k2));
Map<String, Department> deptMap = departments.parallelStream()
.collect(Collectors.toMap(Department::getGridNo, Function.identity(),(k1, k2) -> k2));
10.分组排序
public class Staff {
private int age;
private String name;
private String type;
public Staff() {
}
public Staff(int age, String name, String type) {
this.age = age;
this.name = name;
this.type = type;
}
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;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
Map<String,List<Staff>> groupStaffs = staffs.stream()
.sorted((a, b) -> b.getAge()-a.getAge()).collect(Collectors.groupingBy(s -> s.getType()));