zoukankan      html  css  js  c++  java
  • java8 stream lambda 一个例子

    import java.io.File;
    import java.io.IOException;
    import java.nio.file.Files;
    import java.nio.file.Paths;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.List;
    import java.util.Map;
    import java.util.stream.Collectors;
    import java.util.stream.Stream;
    
    public class Cleaner6 {
    
        public static void main(String[] args) throws IOException, InterruptedException {
            String filePath = args[0];
    
            File originalFodler = new File(filePath);
            String[] fileNames = originalFodler.list();
    
            List<String> keepList = Stream.of(fileNames)
                    .collect(Collectors.groupingBy(t -> t.split("_")[0], 
                            Collectors.groupingBy(t -> t.split("_")[2])))
                    .entrySet().stream().flatMap(p -> {
                        Map<String, List<String>> map = p.getValue();
                        String maxKey = Collections.max(map.keySet());
                        return map.get(maxKey).stream();
                    }).collect(Collectors.toList());
    
            List<String> deleteList = new ArrayList<String>();
            Collections.addAll(deleteList, fileNames);
            deleteList.removeAll(keepList);
            
              
              deleteList.parallelStream().forEach(a->{          
                try {
                    Files.delete(Paths.get(filePath + "\" + a));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
             
    
            System.out.println(fileNames.length);
            System.out.println(keepList.size());
            System.out.println(deleteList.size());
        }
    
    }

    两次group,一次flatmap,并行 foreach。

    感悟:stream出现其实是颠覆循环

  • 相关阅读:
    子查询
    关联,分组练习
    共享锁(S锁)和排它锁(X锁)
    mac 搭建Vue开发环境
    移动端web开发
    负margin
    关于前端的margin
    清除的通用样式 css
    css布局
    <div class="clear"></div>
  • 原文地址:https://www.cnblogs.com/caihemm/p/10591717.html
Copyright © 2011-2022 走看看