【问题标题】:How to sort elements after or before filtering如何在过滤之后或之前对元素进行排序
【发布时间】:2015-12-08 02:18:07
【问题描述】:
public List<Path> removeUnwantedPaths(List<Path> listofPaths, List<String> ids) {
    List<Path> entries;
    entries = listofPaths.stream()
            .filter(p -> ids.contains(p.getParent().getFileName().toString()))
            .collect(Collectors.toList());

    return entries;
}

entries 包含路径元素的列表。元素未排序。我希望按p.getParent().getFileName().toString() 返回的ids 对它们进行排序,以便在我返回集合之前对列表进行组织和排序。如何使用 Java 1.8 groupingBy() 对集合进行分组?所以如果我的列表最初包含以下元素:

212_Hello.txt
312_Hello.txt
516_something.xml
212_Hello.xml

我希望将列表组织为:

212_Hello.txt
212_Hello.xml
312_Hello.txt
516_something.xml

其中 212、312、516 是 ID。

【问题讨论】:

  • 您的问题不清楚?你想返回Map&lt;String, List&lt;Path&gt;&gt;吗?如果不是,您如何将列表中的项目分组?除非您只想对项目进行排序(而不是对它们进行分组)?
  • 所以 id 是父母的文件名?
  • 是的,所以文件路径是这样的/src/resource/files/212/212_Hello.txt
  • 当你想排序时为什么要groupingBy()?为什么不是sort() 成为您的首选?

标签: java arraylist collections java-8 java-stream


【解决方案1】:

以下会做:

public static List<Path> removeUnwantedPaths(List<Path> listofPaths, List<String> ids) {
    return listofPaths.stream()
            .filter(p -> ids.contains(getIdFromPath(p)))
            .sorted(Comparator.comparing(p -> getIdFromPath(p)))
            .collect(Collectors.toList());
}

private static String getIdFromPath(Path p) {
    return p.getParent().getFileName().toString();
}

它会:

  • 使用具有在给定授权 id 列表中的 id 的元素过滤给定列表
  • 根据id升序对流进行排序
  • 返回一个列表

这是基于给定路径总是这样的事实:/src/resource/files/{id}/212_Hello.txt。

【讨论】:

    【解决方案2】:

    这本身并不是分组,分组意味着将唯一 ID 映射到路径。我认为你需要的是结合这两个集合。像这样的

     List<Path> entries;
     entries = listofPaths.stream()
                .filter(p -> ids.contains(p.getParent().getFileName().toString()))
                .map( p -> p.getParent().getFileName() + "_" +p.getFileName())
                .sorted(String::compareTo)
                .map(Paths::get)
                .collect(Collectors.toList());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-16
      • 1970-01-01
      • 2010-09-18
      • 1970-01-01
      • 2012-05-27
      • 1970-01-01
      • 2020-01-30
      • 2019-06-24
      相关资源
      最近更新 更多