java8 新特性使用实例

39 阅读1分钟

不定时更新 小白写法

2023-09-27

java 新特性去重

根据id去重复       

List unique = persons.stream().collect(collectingAndThen(

                toCollection(() -> new TreeSet<>(comparingLong(Person::getId))), ArrayList::new)

        );

    }

// 根据name去重(字符串字段)

 List unique = persons.stream().collect(Collectors.collectingAndThen(

                Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Person::getName))), ArrayList::new));

        unique.forEach(p -> System.out.println(p));

    }

根据条件获取返回

集合获取符合条件的对象 没有返回空

List studentList = new ArrayList<>(); 
studentList.add(new Student(1, "张三", 90)); 
studentList.add(new Studnet(2, "李四", 60)); 
studentList.add(new Student(3, "王五", 30)); 
studentList.add(new Student(4, "赵六", 85)); 
int studentId = 3; 
Student student = studentList.stream().filter(o -> o.getId() == studentId).findAny().orElse(null);

从集合中获取符合条件的数据返回集合

List<PanelGroupDTO> groupDTO = allList.stream().filter(o -> o.getCreateBy().equals(AuthUtils.getUser().getUsername()) && "folder".equals(o.getNodeType())).collect(Collectors.toList());

对象转换

将集合对象 使用方法转换为其他对象的集合对象

List<DynamicMenuDto> pluginDtos = pluginSysMenus.stream().map(this::convert).collect(Collectors.toList()); 


//转化方法
private DynamicMenuDto convert(SysMenu sysMenu) { 
DynamicMenuDto dynamicMenuDto = new DynamicMenuDto(); dynamicMenuDto.setId(sysMenu.getMenuId()); 
dynamicMenuDto.setPid(sysMenu.getPid()); 
return dynamicMenuDto; }

将集合中指定参数集合返回

collect.stream().map(CashDataPublicReportLineDTO::getScheduleLineId).collect(toList())

集合总的参数集合返回并去重

List deviceIds = vos.stream()
                   .map(SysDeviceStatusRecordVo::getDeviceId) 
                   .distinct() .
                   collect(toList());