java8 list转map,list集合中的元素的属性转set,list集合中对象的属性转list,list 排序,list分组...

一.使用java8对list操作

  1.1list转map

1 private Map getMemberMap() {       
2    List members = mberMapper.selectMemberList(new Member());
3    if(CollectionUtils.isEmpty(members)){
4       return null;
5    }
6    return members.stream().collect(Collectors.toMap(Member::getPhone, m -> m, (k1, k2) -> k1)); /** 去重策略,如果有多个相同的key,保留第一个*/
7 }

  1.2list中对象字段转一个list集合

1   public static List getStudentNameList(List list ){
2         List result = list.stream().map(student->student.getName()).collect(Collectors.toList());
3         for (String name : result) {
4             System.out.println("name:"+name);
5         }
6         return result;
7     }

  1.3list中对象字段转一个set集合

  public static Set getStudentNameSet(List list ){
        Set result = list.stream().map(student->student.getName()).collect(Collectors.toSet());
        for (String name : result) {
            System.out.println("name:"+name);
        }
        return result;
    }

   1.4 list 多字段排序,第一个字段降序,第二个字段升序

 1 public static void main(String[] args) {
 2         List sysUserOnlines1= new ArrayList<>();
 3         String date = DateUtils.getDate();
 4         Date date1 = DateUtils.parseDate(date);
 5         System.out.println("date1===="+ date1.toString());
 6         SysUserOnline s1 = new SysUserOnline();
 7         s1.setDateAlloCount(3);
 8         s1.setLastAccessTime(date1);
 9         SysUserOnline s2 = new SysUserOnline();
10         s2.setDateAlloCount(1);
11         s2.setLastAccessTime(DateUtils.addDays(date1,-1));
12         SysUserOnline s3 = new SysUserOnline();
13         s3.setDateAlloCount(2);
14         s3.setLastAccessTime(date1);
15         SysUserOnline s4 = new SysUserOnline();
16         s4.setDateAlloCount(2);
17         s4.setLastAccessTime(DateUtils.addDays(date1,1));
18         sysUserOnlines1.add(s1);
19         sysUserOnlines1.add(s2);
20         sysUserOnlines1.add(s3);
21         sysUserOnlines1.add(s4);
22 
23         System.out.println(sysUserOnlines1.toString());
24         List collect = sysUserOnlines1.stream().sorted(Comparator.comparing(SysUserOnline::getLastAccessTime).reversed().thenComparing(SysUserOnline::getDateAlloCount)).collect(Collectors.toList());
25         System.out.println("=======================");
26         System.out.println(collect.toString());
27     }

 1.5list分组,根据id分组

1 //List 以ID分组 Map>
2 Map> groupBy = appleList.stream().collect(Collectors.groupingBy(Apple::getId));
3 
4 System.err.println("groupBy:"+groupBy);
5 {1=[Apple{id=1, name='苹果1', money=3.25, num=10}, Apple{id=1, name='苹果2', money=1.35, num=20}], 2=[Apple{id=2, name='香蕉', money=2.89, num=30}], 3=[Apple{id=3, name='荔枝', money=9.99, num=40}]}

参照:

 
   

 

转载于:https://www.cnblogs.com/djq-jone/p/10773152.html

你可能感兴趣的:(java8 list转map,list集合中的元素的属性转set,list集合中对象的属性转list,list 排序,list分组...)