java8方法大全

根据一个属性去重

List unique = books.stream().collect( Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.id))), ArrayList::new));

根据两个属性去重

List carseriesConfigurationList = configurations.stream() .collect(Collectors.collectingAndThen(Collectors.toCollection( ()->new TreeSet<>(Comparator.comparing( l -> l.getCarMaterialCode()+l.getCountryArea()))), ArrayList::new));

根据属性值过滤

List libraryList = languageLibraries.stream().filter(l -> StringUtils.isNotEmpty(l.getValue())) .collect(Collectors.toList());

List list = serviceStationUserList.stream().filter(s -> !s.getDefaultLanguage().equals("zh")).collect(Collectors.toList());

取出某一个属性集合

List carMaterialCodes = configurations.stream().map(CarseriesConfiguration::getCarMaterialCode).collect(Collectors.toList());

去除重复对象

doubleKeyList = doubleKeyList.stream().distinct().collect(Collectors.toList());

根据属性值分组

Map> groupList = libraries.stream().collect(Collectors.groupingBy(LanguageLibrary::getKey));

获得某一属性的集合

List serviceStationCode = userList.stream().map(l -> l.getServiceCode() ).collect(Collectors.toList());

List> dictionaryPath = configs.stream() .map(c -> Arrays.asList(new String[]{c.getRegion(), c.getEngineConfig(), c.getModel()})) .collect(Collectors.toList());

获得某一属性的集合并用特殊字符分隔

List list = Stream.of(entity.getRole().split("/")).collect(toList());

将/A/B/C/格式变为数组{A,B,C}

List pathList = Arrays.stream(assemblyToDB.getPath().split("/")) .filter(a -> StringUtils.isNotEmpty(a)) .collect(Collectors.toList());

转换为map结构

Map fieldMap = Arrays.stream(fields).collect(Collectors.toMap(ExcelFieldMap::getExcelColumn, ExcelFieldMap::getFieldName));

转换为set

Set carYears = list.stream().map(CarseriesConfiguration::getCarYear).collect(Collectors.toSet());

排序

//按id从小到大
List sortUser = list.stream().sorted((u1, u2) -> u1.getId().compareTo(u2.getId())).collect(Collectors.toList());

//按id从大到小
List sortUser = list.stream().sorted((u1, u2) -> u2.getId().compareTo(u1.getId())).collect(Collectors.toList());

map 排序 从小到大

// 按照Map的键进行排序
Map sortedMap = codes.entrySet().stream() .sorted(Map.Entry.comparingByKey()) .collect( Collectors.toMap( Map.Entry::getKey, Map.Entry::getValue, (oldVal, newVal) -> oldVal, LinkedHashMap::new ) );

// 按值排序
Map sortedMap2 = codes.entrySet().stream() .sorted(Map.Entry.comparingByValue()) .collect(Collectors.toMap( Map.Entry::getKey, Map.Entry::getValue, (oldVal, newVal) -> oldVal, LinkedHashMap::new));

从大到小

.sorted(Map.Entry.comparingByValue()).reversed()

你可能感兴趣的:(java8方法大全)