java8的stream功能及常用方法


Java8中stream對集合操作做了簡化,用stream操作集合能極大程度簡化代碼。Stream 就如同一個迭代器(Iterator),單向,不可往復,數據只能遍歷一次,遍歷過一次后就用盡了。

一、流的轉換

  Java中的Stream的所有操作都是針對流的,所以,使用Stream必須要得到Stream對象。

  • 初始化stream流
    Stream stream = Stream.of("a", "b", "c");

     

  • 數組轉換為stream流

    String [] strArray = new String[] {"a", "b", "c"};
    stream = Stream.of(strArray);
    或者
    stream = Arrays.stream(strArray);

     

  • 集合對象轉換為一個stream流

    List<String> list = Arrays.asList(strArray);
    stream = list.stream();

二、流的基本操作

  •   遍歷操作(map):使用map操作可以遍歷集合中的每個對象,並對其進行操作,map之后,用.collect(Collectors.toList())會得到操作后的集合。
    //遍歷轉換為大寫
    List<String> output = wordList.stream(). map(String::toUpperCase).collect(Collectors.toList());
    //平方數
    List<Integer> nums = Arrays.asList(1, 2, 3, 4);
    List<Integer> squareNums = nums.stream().map(n -> n * n).collect(Collectors.toList());

     

 

  • 過濾操作(filter):使用filter可以對象Stream中進行過濾,通過測試的元素將會留下來生成一個新的Stream。
    //去點空值
    List<String> filterLists = new ArrayList<>();
    filterLists.add("");
    filterLists.add("a");
    filterLists.add("b");
    List afterFilterLists = filterLists.stream().filter(s -> !s.isEmpty())
            .collect(Collectors.toList());
    
    //遞歸判斷得到子數據
    private List<MenuDto> convertTree(List<MenuDto> menus,Long parentId) {
            List<MenuDto> targetList = new ArrayList<>();
            List<MenuDto> menuList = menus.stream().filter(item -> item.getParentId().equals(parentId)).collect(Collectors.toList());
            menuList.forEach(item ->{
                targetList.add(new MenuDto(item.getId(),
                        item.getUrl(),
                        item.getPath(),
                        item.getComponent(),
                        item.getName(),
                        item.getIconCls(),
                        item.getParentId(),
                        item.getEnabled(),
                        item.getSort(),
                        item.getRoles(),
                        convertTree(menus,item.getId()),
                        item.getMeta()));
            });
            //根據權重逆序
            List<MenuDto> targetList1=targetList.stream().sorted(Comparator.comparing(MenuDto::getSort).reversed()).collect(Collectors.toList());
            return targetList1;
        }

     

  • 循環操作(forEach):如果只是想對流中的每個對象進行一些自定義的操作,可以使用forEach。
    List<String> forEachLists = new ArrayList<>();
    forEachLists.add("a");
    forEachLists.add("b");
    forEachLists.add("c");
    
    forEachLists.stream().forEach(s-> System.out.println(s));
  • 返回特定的結果集合(limit/skip):limit 返回 Stream 的前面 n 個元素;skip 則是扔掉前 n 個元素。
    //skip與limit是有順序關系
    List<String> forEachLists = new ArrayList<>();
    forEachLists.add("a");
    forEachLists.add("b");
    forEachLists.add("c");
    forEachLists.add("d");
    forEachLists.add("e");
    forEachLists.add("f");
    List<String> limitLists = forEachLists.stream().skip(2).limit(3).collect(Collectors.toList());
  • 排序(sort/min/max/distinct):sort可以對集合中的所有元素進行排序。max,min可以尋找出流中最大或者最小的元素,而distinct可以尋找出不重復的元素。
    //對一個集合進行排序
    List<Integer> sortLists = new ArrayList<>();
    sortLists.add(1);
    sortLists.add(4);
    sortLists.add(6);
    sortLists.add(3);
    sortLists.add(2);
    List<Integer> afterSortLists = sortLists.stream().sorted((In1,In2)->
    
           In1-In2).collect(Collectors.toList());
    
    //自然序列
    List<Student> studentList1=studentList.stream().sorted().collect(Collectors.toList());
    //逆序
    List<Student> studentList2=studentList.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
    //根據年齡自然順序
    List<Student> studentList3=studentList.stream().sorted(Comparator.comparing(Student::getAge)).collect(Collectors.toList());
    //根據年齡逆序
    List<Student> studentList4=studentList.stream().sorted(Comparator.comparing(Student::getAge).reversed()).collect(Collectors.toList());
    //打印
    studentList4.forEach(student -> System.out.println("id is "+student.getId()+" ;name is "+student.getName()+";age is "+student.getAge()));

    //得到其中長度最大的元素:
    List<String> maxLists = new ArrayList<>();
    maxLists.add("a");
    maxLists.add("b");
    maxLists.add("c");
    maxLists.add("d");
    maxLists.add("e");
    maxLists.add("f");
    maxLists.add("hahaha");
    int maxLength = maxLists.stream().mapToInt(s->s.length()).max().getAsInt();
    System.out.println("字符串長度最長的長度為"+maxLength);
    //對一個集合進行查重
    List<String> distinctList = new ArrayList<>(); distinctList.add("a"); distinctList.add("a"); distinctList.add("c"); distinctList.add("d"); List<String> afterDistinctList = distinctList.stream().distinct().collect(Collectors.toList());
  • 匹配(Match方法):有的時候,我們只需要判斷集合中是否全部滿足條件,或者判斷集合中是否有滿足條件的元素,這時候就可以使用match方法:

    allMatch:Stream 中全部元素符合傳入的 predicate,返回 true
    anyMatch:Stream 中只要有一個元素符合傳入的 predicate,返回 true

    noneMatch:Stream 中沒有一個元素符合傳入的 predicate,返回 true

    //判斷集合中沒有有為‘c’的元素
    List<String> matchList = new ArrayList<>();
    matchList.add("a");
    matchList.add("a");
    matchList.add("c");
    matchList.add("d"); 
    boolean isExits = matchList.stream().anyMatch(s -> s.equals("c"));
    
    //判斷集合中是否全不為空
    List<String> matchList = new ArrayList<>();
    matchList.add("a");
    matchList.add("");
    matchList.add("a");
    matchList.add("c");
    matchList.add("d");
    boolean isNotEmpty = matchList.stream().noneMatch(s -> s.isEmpty());

     


免責聲明!

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



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