一.使用java8对list操作
1.1list转map
private Map<String, Member> getMemberMap() {
List<Member> members = mberMapper.selectMemberList(new Member());
if(CollectionUtils.isEmpty(members)){
return null;
}
return members.stream().collect(Collectors.toMap(Member::getPhone, m -> m, (k1, k2) -> k1)); /** 去重策略,如果有多个相同的key,保留第一个*/
}
1.2list中对象字段转一个list集合
public static List<String> getStudentNameList(List<Student> list ){
List<String> result = list.stream().map(student->student.getName()).collect(Collectors.toList());
for (String name : result) {
System.out.println("name:"+name);
}
return result;
}
1.3list中对象字段转一个set集合
public static Set<String> getStudentNameSet(List<Student> list ){
Set<String> result = list.stream().map(student->student.getName()).collect(Collectors.toSet());
for (String name : result) {
System.out.println("name:"+name);
}
return result;
}
1.4 list 多字段排序,第一个字段降序,第二个字段升序
public static void main(String[] args) {
List<SysUserOnline> sysUserOnlines1= new ArrayList<>();
String date = DateUtils.getDate();
Date date1 = DateUtils.parseDate(date);
System.out.println("date1===="+ date1.toString());
SysUserOnline s1 = new SysUserOnline();
s1.setDateAlloCount(3);
s1.setLastAccessTime(date1);
SysUserOnline s2 = new SysUserOnline();
s2.setDateAlloCount(1);
s2.setLastAccessTime(DateUtils.addDays(date1,-1));
SysUserOnline s3 = new SysUserOnline();
s3.setDateAlloCount(2);
s3.setLastAccessTime(date1);
SysUserOnline s4 = new SysUserOnline();
s4.setDateAlloCount(2);
s4.setLastAccessTime(DateUtils.addDays(date1,1));
sysUserOnlines1.add(s1);
sysUserOnlines1.add(s2);
sysUserOnlines1.add(s3);
sysUserOnlines1.add(s4);
System.out.println(sysUserOnlines1.toString());
List<SysUserOnline> collect = sysUserOnlines1.stream().sorted(Comparator.comparing(SysUserOnline::getLastAccessTime).reversed().thenComparing(SysUserOnline::getDateAlloCount)).collect(Collectors.toList());
System.out.println("=======================");
System.out.println(collect.toString());
}
1.5list分组,根据id分组
//List 以ID分组 Map<Integer,List<Apple>>
Map<Integer, List<Apple>> groupBy = appleList.stream().collect(Collectors.groupingBy(Apple::getId));
System.err.println("groupBy:"+groupBy);
{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}]}
1.6list根据条件去重过滤
List<ResourceHighFile> highFiles = new ArrayList<>();
Set<ResourceHighFile> set = new TreeSet<ResourceHighFile>((file1, file2) -> file1.getFileName().compareTo(file2.getFileName()));
set.addAll(highFiles);
//根据getName去重
personList = personList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(
() -> new TreeSet<>(Comparator.comparing(Person::getName))), ArrayList::new));
1.7list去除空元素
list.removeAll(Collections.singleton(null));