Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

sorting

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"

like image 589
DanielD Avatar asked Mar 24 '16 21:03

DanielD


1 Answers

Java 8:

videos.sort(Comparator.comparing(v->nameIdList.indexOf(v.getNameId())));

this is smaller than this

like image 65
Tokala Sai Teja Avatar answered Sep 20 '22 13:09

Tokala Sai Teja