Java8 List通用方法處理總結


總結項目里使用Java8新特性對List的數據處理(用的比較多的)。

一、分組

Map<String, List<T>> yearData = allData.stream().collect(Collectors.groupingBy(T::getYear));

二、條件篩選

單條件篩選

List<T> filterList = appleList.stream().filter(a -> a.getName().equals("YC")).collect(Collectors.toList());

多條件篩選

List<T> filterList = dayVoList.
                      stream().filter(a -> a.getYEAR().equals(item)).collect(Collectors.toList())
                      .stream().filter(a -> a.getPrice() != "0" && a.getPrice() != "0.0").collect(Collectors.toList());

三、List合並

1.合並去重

List<String> result = Stream.of(Lists.newArrayList("A", "B", "C"), Lists.newArrayList("A", "B"))
  .flatMap(Collection::stream).distinct().collect(Collectors.toList());

 

1.合並不去重

List<String> result = Stream.of(Lists.newArrayList("A", "B", "C"), Lists.newArrayList("A", "B"))
  .flatMap(Collection::stream).collect(Collectors.toList());

四、List排序

1.倒序

List<T> api_list = apiData
               .stream().sorted(Comparator.comparing(T::getID).reversed()).collect(Collectors.toList());

2.正序

List<T> api_list = apiData
               .stream().sorted(Comparator.comparing(T::getID).collect(Collectors.toList());

五、List 數據去重

List<T> primaryFilterData = apiData.stream().collect(
               Collectors.collectingAndThen(
                       Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(T::getName))), ArrayList::new));

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM