Search code examples
javaenumscomparable

Sort a set of elements by their field


i have a set A of objects from the same class, and each of them has an Enum field ,which is comparable. how can i sort the set by that field? i thought about something like:

Collections.sort(A, enumField)

but of course that enumField is not an object to be compared by...


Solution

  • Collections.sort does not accept a Set. It only accepts Lists, so first you should convert your set to a list:

    ArrayList<YourObject> list = new ArrayList<>(yourSet);
    

    Then you can call Collections.sort with a custom comparator:

    Collections.sort(list, Comparator.comparing(x -> x.enumField));
    // now "list" contains the sorted elements.