2

I have List of Student object

And the Student object has

public class Student{

    private String name;
    private String town;

    // getters,setters and toString method

}

And my List<Student> looks like :

List<Student> list = new ArrayList<Student>();
list.add(new Student("abc","xtown"));
list.add(new Student("bcd","ytown"));
list.add(new Student("cdf","xtown"));
list.add(new Student("fgh","Atown"));

And another list is

List<String> list1 = new ArrayList<>();
list1.add("bcd");
list1.add("cdf");
list1.add("fgh");
list1.add("abc"); 

I need to sort the list based on list1.

My output would be

[Student [name=bcd,town=ytown], 
 Student [name=cdf,town=xtown], 
 Student [name=fgh,town=Atown], 
 Student [name=abc,town=xtown]]
Bentaye
  • 9,403
  • 5
  • 32
  • 45
madhuri
  • 103
  • 2
  • 11
  • 2
    The answer to this seems like it could match your issue: https://stackoverflow.com/questions/18129807/in-java-how-do-you-sort-one-list-based-on-another – endaS Mar 28 '19 at 09:12
  • Possible duplicate of [In Java how do you sort one list based on another?](https://stackoverflow.com/questions/18129807/in-java-how-do-you-sort-one-list-based-on-another) – Ondra K. Mar 28 '19 at 09:18
  • @OndraK. No the link not answer the OP's problem – Youcef LAIDANI Mar 28 '19 at 10:06

3 Answers3

1

What about using java 8 like so :

list.sort(Comparator.comparing(Student::getName,
                               Comparator.comparing(list1::indexOf)));
Bentaye
  • 9,403
  • 5
  • 32
  • 45
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
1

While YCF_L's answer is probably the most elegant, I feel that a simpler to understand solution can be of use for the original poster, here is one

First, create a list of same size as the list you want to sort and initialize all the elements to null:

List<Student> sortedList = new ArrayList<>(Collections.nCopies(list.size(), null));

Then, go through your Student list and add them at the correct index

With a simple for loop:

int index;
for(Student student : list) {
    index = list1.indexOf(student.getName());
    sortedList.set(index, student);
}

Or using forEach:

list.forEach(student -> {
    int index = list1.indexOf(student.getName());
    sortedList.set(index, student);
});

The corresponding One-liner:

list.forEach(s -> sortedList.set(list1.indexOf(s.getName()), s));
Bentaye
  • 9,403
  • 5
  • 32
  • 45
0

You can create your own custom comparator.

Comparator<Student> comparator = new Comparator<Student>()
{
    @Override
    public int compare(Student o1, Student o2)
    {
        int index1 = list1.indexOf(o1.getName());
        int index2 = list1.indexOf(o2.getName());

        return Integer.compare(index1 , index2 );
    }
};

and than sort :)

java.util.Collections.sort(yourList, comparator);
Adir Dayan
  • 1,308
  • 13
  • 21
  • list1 is a list of String, not of Student, I think you wanted to write `list1.indexOf(o1.getName())` and `list1.indexOf(o2.getName())` – Bentaye Mar 28 '19 at 10:10