list 与lambda

lambda 各种操作list 合集

使用hibernate validator出现上面的错误, 需要 注意
@NotNull 和 @NotEmpty  和@NotBlank 区别
@NotEmpty 用在集合类上面
@NotBlank 用在String上面
@NotNull    用在基本类型上
在枚举类上不要加非空注解

日期排序

升序
msgList.sort((Message m1, Message m2) -> m2.getSendDate().compareTo(m1.getSendDate()));

降序
msgList.sort(Comparator.comparing(Message::getSendDate, Comparator.nullsLast(Date::compareTo)));

交集、并集、差集

 // 交集
List<String> intersection = list1.stream().filter(item -> list2.contains(item)).collect(toList());
System.out.println("---得到交集 intersection---");
intersection.parallelStream().forEach(System.out :: println);

// 差集 (list1 - list2)
List<String> reduce1 = list1.stream().filter(item -> !list2.contains(item)).collect(toList()); System.out.println("---得到差集 reduce1 (list1 - list2)---");
reduce1.parallelStream().forEach(System.out :: println);

// 差集 (list2 - list1)
List<String> reduce2 = list2.stream().filter(item -> !list1.contains(item)).collect(toList());
System.out.println("---得到差集 reduce2 (list2 - list1)---");
reduce2.parallelStream().forEach(System.out :: println);

 // 并集
 List<String> listAll = list1.parallelStream().collect(toList());
List<String> listAll2 = list2.parallelStream().collect(toList());
 listAll.addAll(listAll2);
 System.out.println("---得到并集 listAll---");
 listAll.parallelStream().forEach(System.out :: println);

 // 去重并集
List<String> listAllDistinct = listAll.stream().distinct().collect(toList());
System.out.println("---得到去重并集 listAllDistinct---"); listAllDistinct.parallelStream().forEach(System.out :: println);

System.out.println("---原来的List1---");
list1.parallelStream().forEach(System.out :: println);
System.out.println("---原来的List2---");
list2.parallelStream().forEach(System.out :: println);

// 一般有filter 操作时,不用并行流parallelStream ,如果用的话可能会导致线程安全问题

id相同赋值

List<UserCourseKnowledgeDetailVO> finalList = new ArrayList<>();
if(CollectionUtils.isNotEmpty(validityList)){
    validityList.forEach(operateCourseKnowledgeUserValidity->
            userCourseKnowledgeDetailVOList.stream()
                    .filter(userCourseKnowledgeDetailVO->userCourseKnowledgeDetailVO.getId().equals(operateCourseKnowledgeUserValidity.getKnowledgeId()))
                    .forEach(userCourseKnowledgeDetailVO-> userCourseKnowledgeDetailVO.setLastLearnTime(operateCourseKnowledgeUserValidity.getUpdateTime()))
    );

排除自己

排除自己
list = list.stream().filters -> !"a".equals(s)).collect(Collectors.toList());

return Optional.ofNullable(matchRole).map(MatchRole::getInitScore).orElse(null);
MAP TO LONG
 String ids= "1,2,3,4,5,6";  
 List<Long> listIds = Arrays.asList(ids.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());  
 System.out.println(Arrays.toString(listIds .toArray()));//[1,2,3,3,4,5,6]  

去重

List<String> dataList = list.stream().distinct().collect(Collectors.toList());


//根据id去重
personList = personList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(
                // 利用 TreeSet 的排序去重构造函数来达到去重元素的目的
                // 根据firstName去重
                () -> new TreeSet<>(Comparator.comparing(Person::getName))), ArrayList::new));

取几条排序

//取学习时长最大的两条 从高到低排序
List<OperateCourseKnowledgeUserValidity> topTwoList = list.stream()
        .sorted(Comparator.comparing(OperateCourseKnowledgeUserValidity::getStudyTimes).reversed())
        .limit(2)
        .collect(Collectors.toList());

分组,遍历分组

     //分组
        Map<String, List<User>> groupBySex = userList.stream().collect(Collectors.groupingBy(User::getSex));
        //遍历分组
        for (Map.Entry<String, List<User>> entryUser : groupBySex.entrySet()) {
            String key = entryUser.getKey();
            List<User> entryUserList = entryUser.getValue();
        }

合并userId 相同的courseNum

/**
 * 合并userId 相同的courseNum
 * @param oldList
 * @return
 */
public static List<UserCourseTimeStatisVO> getNewList(List<UserCourseTimeStatisVO> oldList) {
    HashMap<Long, UserCourseTimeStatisVO> tempMap = new HashMap<Long, UserCourseTimeStatisVO>();

    // 去掉重复的key
    for (UserCourseTimeStatisVO userCourseTimeStatisVO : oldList) {
        Long userId = userCourseTimeStatisVO.getUserId();
        // containsKey(Object key)该方法判断Map集合中是否包含指定的键名,如果包含返回true,不包含返回false
        // containsValue(Object value)该方法判断Map集合中是否包含指定的键值,如果包含返回true,不包含返回false
        if (tempMap.containsKey(userId)) {
            UserCourseTimeStatisVO newList = new UserCourseTimeStatisVO();
            newList.setUserId(userId);
            // 合并相同key的value
            newList.setCourseNum(tempMap.get(userId).getCourseNum() + userCourseTimeStatisVO.getCourseNum());
            // HashMap不允许key重复,当有key重复时,前面key对应的value值会被覆盖
            tempMap.put(userId, newList);
        } else {
            tempMap.put(userId, userCourseTimeStatisVO);
        }
    }
    List<UserCourseTimeStatisVO> newList = new ArrayList<UserCourseTimeStatisVO>();
    Iterator iter = tempMap.entrySet().iterator();
    while (iter.hasNext()) {
        Map.Entry entry = (Map.Entry) iter.next();
        UserCourseTimeStatisVO newPerson = (UserCourseTimeStatisVO) entry.getValue();
        newList.add(newPerson);
    }
    return newList;
}

获取属性

 List<Integer> idList = list1.stream().map(User::getId).collect(Collectors.toList());

 List<User> userList1 = list1.stream().filter(user2 -> idList.contains(user2.getId())).collect(Collectors.toList());
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容