java8中新特性

将list转化为map

1
2
3
4
5
6
7
8
9
10
11
12
13
public class toMap {
public static void main(String[] args) {
List<p> person = new ArrayList<>();
person.add(new p("yu","18"));
person.add(new p("min","38"));
person.add(new p("tao","28"));
person.add(new p("tao","28"));

Map<String, String> collect = person.stream().distinct().collect(Collectors.toMap(p::getName, p::getAge));
System.out.println(collect);

}
}

这里需要注意,因为上面list转map时key会重复也就会报错,所以我们需要去重,要使用distinct()方法,但是还是会报错,因为我们没有定义equalshashCode方法,去pojo类定义完即可,对一个自定义的class使用distinct(),切记覆写equals()和hashCode()方法

排序

1
2
3
4
5
6
7
8
9
10
11
12
//默认从小到大排序
Integer[] i = {1,5,3,65,986,4,2,4,5};
Stream<Integer> stream = Arrays.stream(i);
stream.sorted().forEach(System.out::println);
// 按照姓名排序
List<DcInterview> list = dcInterviewMapper.getList(param);
list.sort(Comparator.comparing(Employee::getName));
@Data
class Employee {
String name;
int age;
}
赏个🍗吧
0%