How can I sort a list in java by another list of ids

Viewed 17670

I have a list of objects in java that looks something like this:

List<Video> videos = new ArrayList<Video>();

and my video object looks like this:

public class Video {
    private String nameId;
    private Integer id;
    ...
}

I have another list that just has my nameId strings:

List<String> nameIdList = ArrayList<String>();

How can I write a compareto method that doesn't sort my list of videos by comparing each video and instead uses another list? My approach so far has been to use a simple bubble sort but that will be very inefficient as my list gets bigger

Example:

I could have video objects with nameIds : "apple", "bannana", "orange"

and my list of strings to sort them by could be: "bannana", "apple", "orange"

so my videos I would want to return to my client should be in the order of: "bannana", "apple", "orange"

6 Answers

You can use Java 8 stream

List<Video> orderedList=
              nameIdList.stream()
                  .map(
                      s ->
                          videos.stream()
                              .filter(v -> v.get_id().equals(s))
                              .findFirst()
                              .orElse(null))
                  .collect(Collectors.toList());
              
Related