Java8新特性集合相关的一些实用方法

工作日常中经常用到的方法

本人日常工作的一些积累,经常用又容易忘,写个博客记录一下。

获取list中重复元素

//根据Attendance类中的staffCode属性查重,并将重复数据放到repetition集合中
List<String> repetition =new ArrayList<>();
attendanceList.stream().collect(Collectors.groupingBy(Attendance::getStaffCode)).values().stream()
        .filter(attendances -> attendances.size() > 1)
        .map(attendances -> attendances.get(0))
        .forEach(attendance -> repetition.add(attendance.getStaffCode()));
if(!repetition.isEmpty()){
    jsonResponseVO.setSuccess(Boolean.FALSE);
    jsonResponseVO.setReason("员工工号为" + repetition.get(0) + "重复,请检查!");
    return jsonResponseVO;
}

获取两个list中重复元素

//主要是通过stream中的filter函数以及contains函数做出筛选
final List<Long> employeeIds = payrollCheckRepository.queryCorrectEmpIds(empType, condition.getPayrollCheckViewCode(), checkoutYM);
List<Long> selectedEmployeeIds=payrollCheckRepository.queryOtherEmpIds(Long.valueOf(PAYROLL_CHECK_EMP_SELECT.getRetCode()),condition.getPayrollCheckViewCode(),condition.getCheckoutYM());
if(!selectedEmployeeIds.isEmpty()){
    List<Long> ids=employeeIds.stream().filter(item ->selectedEmployeeIds.contains(item)).collect(Collectors.toList());
    if(!ids.isEmpty()){
        String staffCode=employeeService.queryEmployeeById(ids.get(0)).getStaffCode();
        returnInfo.setSuccess(Boolean.FALSE);
        returnInfo.setReason("员工工号为"+staffCode+"已存在于其他核算表中,请检查!");
        return returnInfo;
    }
}

1.获取list对象中某个元素的新集合

List<String> excelStaffList = attendanceList.stream().map(Attendance::getStaffCode).collect(Collectors.toList());

去除list中空对象

List<Dependant> dependantList =entities.stream().filter(d -> !StringUtils.isEmpty(d.getDependantName())).collect(Collectors.toList());

list去除重复数据(非实体类)

List uniqueStr = list.stream().distinct().collect(Collectors.toList());

list去除重复数据(根据对象属性)

List<InsuredRule> deleteList = insuredRuleList.stream().collect(
                    collectingAndThen(
                            toCollection(() -> new TreeSet<>(Comparator.comparing(InsuredRule::getRuleName))), ArrayList::new)
            );

获取list中符合条件的集合

List<Workflow> collect = list.stream().filter(workFlow -> workFlow .getWorkflowName().equals(condition.getWorkflowName())).collect(Collectors.toList());

实现list交集/并集/差集/去重并集

		List<String> list1 = new ArrayList();
        list1.add("11");
        list1.add("22");
        list1.add("33");

        List<String> list2 = new ArrayList();
        list2.add("33");
        list2.add("44");
        list2.add("55");

        // 交集
        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);

List转Map

id为key,apple对象为value,可以这么做:
/**
 * List -> Map
 * 需要注意的是:
 * toMap 如果集合对象有重复的key,会报错Duplicate key ....
 *  两个对象的id都为1。
 *  可以用 (k1,k2)->k1 来设置,如果有重复的key,则保留key1,舍弃key2
 */
Map<Integer, Apple> appleMap = appleList.stream().collect(Collectors.toMap(Apple::getId, a -> a,(k1,k2)->k1));

List里面的对象元素,以某个属性来分组,例如,以id分组,将id相同的放在一起

Map<Integer, List<Apple>> groupBy = appleList.stream().collect(Collectors.groupingBy(Apple::getId));

一个强大的并发类CopyOnWriteArrayList(可以对数据边读边操作:比如即时删除list的元素而不报错)

CopyOnWrite容器即写时复制的容器。通俗的理解是当我们往一个容器添加元素的时候,不直接往当前容器添加,而是先将当前容器进行Copy,
复制出一个新的容器,然后新的容器里添加元素,添加完元素之后,再将原容器的引用指向新的容器。这样做的好处是我们可以对CopyOnWrite容器进行并发的读,
而不需要加锁,因为当前容器不会添加任何元素。所以CopyOnWrite容器也是一种读写分离的思想,读和写不同的容器。

CopyOnWriteArrayList<PayrollCheckView> payrollCheckViews =new CopyOnWriteArrayList<>(viewList);
for (PayrollCheckView payrollCheckView:payrollCheckViews) {
	if(StringUtils.isNotEmpty(payrollCheckView.getStaffIds())){
		List<Long> staffIds= Arrays.stream(payrollCheckView.getStaffIds().split(",")).map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
		if (!staffIds.isEmpty()&&!availableIds.containsAll(staffIds)){
			payrollCheckViews.remove(payrollCheckView);
		}
	}
}
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值