java8 集合笔记

class User(){
private String userCode;
private String userName;
}

List userList;

//list 集合提取字段数组
String [] productCodes = userList.stream().map(User::getUserCode).toArray(String[]::new);

//list 集合提取某个字段 转换为新的list
List userCodes = userList.stream().map(user->user.getUserCode()).collect(Collectors.toList());

//list 按照字段分组 依据字段等值的 放在同一个集合并指向KEY    
Map> userListMap = userList.stream().collect(Collectors.groupingBy(User::getUserCode));

//list过滤筛选集合
List userList = userList .stream().filter(er -> er.getUserName().equals("张三")).collect(Collectors.toList());


// 根据字段过滤去重
List rs = new ArrayList<>();
List checkUserList = userList.stream().filter(
v -> {
boolean flag = !rs.contains(v.getUserName());
rs.add(v.getUserName());
return flag;
}).collect(Collectors.toList());

//list集合排序
List sysMenus;
//第一种
sysMenus.sort((o1, o2) -> o1.getSort().compareTo(o2.getSort()));
//第二种
Collections.sort(sysMenus,(s1,s2) -> s1.getSort().compareTo(s2.getSort()));



// 需要筛选的条件:从stuList中筛选出年龄为21和22的学生
List ageList = new ArrayList();
ageList.add(21);
ageList.add(22);

// JDK1.8提供了lambda表达式, 可以从stuList中过滤出符合条件的结果。
// 定义结果集
List result = null;
result = stuList.stream()
.filter((Student s) -> ageList.contains(s.getAge()))
.collect(Collectors.toList());

 

//取最大值

Optional userOp= result.stream().
max(Comparator.comparingInt(Student ::getAge));
Student maxDay = userOp.get();


//拓展工具  list转map
public static  Map listToMap(List list, String keyField){
        Map result = new HashMap<>();
        if(list != null && list.size() > 0 && StringUtils.isNotEmpty(keyField)){
            String firstLetter = keyField.substring(0, 1).toUpperCase();
            String getter = "get" + firstLetter + keyField.substring(1);
            try {
                for(Object obj : list){
                    Method method = obj.getClass().getMethod(getter,null);
                    K key = (K) method.invoke(obj,null);
                    if(key != null && StringUtils.isNotEmpty(key.toString())){
                        result.put(key,(V) obj);
                    }
                }
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
 

 

你可能感兴趣的:(java8 集合笔记)