技术交流28群

服务热线

135-6963-3175

微信服务号

java8 lambda表达式 更新时间 2022-3-24 浏览2244次

1、取对象集合中某字段集合

List<String> ids= users.stream().map(User::getServiceId).collect(Collectors.toList())

2、对象集合按字段排序(以下为倒序)

users.stream().sorted(Comparator.comparing(User::getAge).reversed()).collect(Collectors.toList());

3、forEach遍历

users.stream().forEach(obj->{
            ids.add(obj.getId());
            ids.add(obj.getName());
        });

4、list中某两个字段转map

Map<String, String> nameMaps = orgs.stream().collect(Collectors.toMap(User::getId, User::getName));

value为实体时:

Map<Long,User> map = users.stream().collect(Collectors.toMap(User::getId,user -> user));

5、group by分组

按age进行分组:

Map<Integer, List<User>> personGroups = Stream.generate(new User()).collect(Collectors.groupingBy(User::getAge));

方式二:

Map<Integer, List<User>> userMaps =users.stream().collect(Collectors.groupingBy(User::getAge));

6、对list对象里的字段进行分组,并把另一个字段放入list

Map<Integer,List<String>> map=users.stream().collect(Collectors.groupingBy(User::getAge,Collectors.mapping(User::getName,Collectors.toList())));

7、对map-list进行排序

Map<Integer,List<String>> map1 = new HashMap<>();
map1.put(4,Lists.newArrayList("1","2","7","8","5"));
map1.put(3,Lists.newArrayList("5"));
map1.put(1,Lists.newArrayList("1","2","8","5"));
map1.put(2,Lists.newArrayList("2","2","8"));
//排序
Map<Integer,List<String>> sorted = map1.entrySet().stream()
        .sorted(Comparator.comparingInt(e->e.getValue().size()))
        .collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue,(a,b) -> {throw new AssertionError();},LinkedHashMap::new));
Map<Integer,List<String>> reverdMap=new LinkedHashMap<Integer,List<String>>();
//倒序
ListIterator<Map.Entry<Integer,List<String>>> i = new ArrayList<Map.Entry<Integer,List<String>>>(sorted.entrySet()).listIterator(sorted.size());
while(i.hasPrevious()) {
    Map.Entry<Integer,List<String>> entry=i.previous();
    reverdMap.put(entry.getKey(),entry.getValue());
}
for(Integer key:reverdMap.keySet()){
    System.out.println(reverdMap.get(key));
}