Java – sort elements by field

I have a set of objects from the same class, and each object has an enum field, which is comparable

Collections.sort(A,enumField)

But of course enumfield is not an object that can be compared

Solution

Collections. Sort does not accept set It only accepts lists, so first you should convert your set to a list:

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

You can then use a custom comparator to call collections sort:

Collections.sort(list,Comparator.comparing(x -> x.enumField));
// Now "list" contains the sorted elements.
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>