M06H
M06H

Reputation: 1783

How to sort elements after or before filtering

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 contain a list of path element. The elements are not sorted. Im looking to sort them by ids returned by p.getParent().getFileName().toString() so that the list is organised and sorted before I return the collection. How can I use Java 1.8 groupingBy() to group the collection? So If my list contains the following elements initially:

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

I want the list to be organised as:

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

where 212, 312, 516 are the ids.

Upvotes: 4

Views: 2904

Answers (2)

Tunaki
Tunaki

Reputation: 137229

The following will do:

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();
}

It will:

  • filter the given List with elements having an id that is in the given list of authorized ids
  • sort the stream according to the id in ascending order
  • return a list of that

It is based on the fact that the given paths are always like this: /src/resource/files/{id}/212_Hello.txt.

Upvotes: 3

Sleiman Jneidi
Sleiman Jneidi

Reputation: 23339

This is not grouping per se, grouping means mapping unique ids to paths. I think what you need is combining both collections. something like this

 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());

Upvotes: 1

Related Questions