1

I have an object list and a string array as below. How can I sort my object list according to my array? Is it possible to do with java comparator and collection.sort() ?

Grade Object

Class Grade{
   private Long keyId;
   private String gradeName;
   private int classCount;
}

Grade List

 List<Grades> grades= new ArrayList<>();

String Array

String[] gradeOrder= {"year 1", "year 2", "year 3", "year 4"};
3
  • The easy solution is to have the Grades object implement Comparable then you can simply use Collections.sort(grades, yourCustomComparator); where Comparator<Grades> yourCustomComparator = (Grades g1, Grades g2) -> g1.gradeName.compareTo( g2.gradeName);. This will use normal string sorting which thankfully we can use for your list because year 1 to year 4 are all in order already. Commented Apr 12, 2021 at 4:11
  • @sorifiend what if array like below ? String[] gradeOrder= {"year 3", "year 2", "year 1", "year 4"}; Commented Apr 12, 2021 at 4:34
  • 2
    Then your code could get messy fast and I would encourage you use an enum that represents a varue that works with a comparator for example String YEAR_3 = "sort_1"; and String YEAR_2 = "sort_2"; Or map the whole list and use that as your Comparator Commented Apr 12, 2021 at 4:40

2 Answers 2

2

Try this.

List<Grade> grades = new ArrayList<>();
// add Grade instances to grades
String[] gradeOrder = {"year 1", "year 2", "year 3", "year 4"};
Map<String, Integer> gradeMap = IntStream.range(0, gradeOrder.length)
    .boxed()
    .collect(Collectors.toMap(i -> gradeOrder[i], Function.identity()));

Collections.sort(grades,
    Comparator.comparing(grade -> gradeMap.get(grade.getGradeName())));
Sign up to request clarification or add additional context in comments.

Comments

0

Use List.sort(Comparator<? super E> c), provide a custom Comparator which contains an order structure (your gradeOrder array), or implement equals() method for your Grade class for more convinent comparing (but you may lost custom order ability by providing a certain order structure).

https://docs.oracle.com/javase/8/docs/api/java/util/List.html

You may want to try some library like lombok, which has a @EqualsAndHashCode annotation to auto generate these methods for you class.

https://projectlombok.org/features/EqualsAndHashCode

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.