java8方法大全

根据一个属性去重

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

根据两个属性去重

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

根据属性值过滤

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

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

取出某一个属性集合

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

去除重复对象

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

根据属性值分组

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

获得某一属性的集合

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

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

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

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

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

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

转换为map结构

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

转换为set

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

排序

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

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

map 排序 从小到大

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

// 按值排序
Map<String, Integer> 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()

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容