Sort by given index sequence using Stream

Lester L. :

Im trying think if this sorting by index is possible using streams. All my searches always point to sorting by comparing object value into other object value. Below is the example data and the expected results :

List<Movie> movies = new ArrayList<>();
movies.add(new Movie(1, "Movie1"));
movies.add(new Movie(2, "Movie2"));
movies.add(new Movie(3, "Movie3"));
movies.add(new Movie(4, "Movie4"));

int[] sortIndex = [0, 3, 1, 2];
...Sorting Code...
for (Movie movie : movies) {
    Log.d(TAG, movie.getName());
}

Expected answer should be

Movie1
Movie4
Movie2
Movie3
GBlodgett :

One easy way to do this is iterate over the Array, and then map each int to the corresponding index of the List, and then collect that to a List:

List<Movie> newList = Arrays.stream(sortIndex)
                            .mapToObj(e -> movies.get(e))
                            .collect(Collectors.toList());

Which will produce the List:

[Movie1, Movie4, Movie2, Movie3]

You can create a method to do this:

public <T> List<T> sortList(int[] sortOrder, List<T> list) {
    return Arrays.stream(sortOrder)
                 .mapToObj(e -> list.get(e))
                 .collect(Collectors.toList());
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=152937&siteId=1