Assuming you actually have a List<AnObject>, all you need is
list.sort(Comparator.comparing(a -> a.attr));
If you make you code clean by not using public fields, but accessor methods, it becomes even cleaner:
list.sort(Comparator.comparing(AnObject::getAttr));
Answer from JB Nizet on Stack OverflowAssuming you actually have a List<AnObject>, all you need is
list.sort(Comparator.comparing(a -> a.attr));
If you make you code clean by not using public fields, but accessor methods, it becomes even cleaner:
list.sort(Comparator.comparing(AnObject::getAttr));
As a complement to @JB Nizet's answer, if your attr is nullable,
list.sort(Comparator.comparing(AnObject::getAttr));
may throw a NPE.
If you also want to sort null values, you can consider
list.sort(Comparator.comparing(a -> a.attr, Comparator.nullsFirst(Comparator.naturalOrder())));
or
list.sort(Comparator.comparing(a -> a.attr, Comparator.nullsLast(Comparator.naturalOrder())));
which will put nulls first or last.
Videos
If there are only four possible values that your code variable can take, you could save them in a map and compare the values when sorting your list:
public static void main(String[] args) {
List<MyObject> myObjects = new ArrayList<>();
myObjects.add(new MyObject("fName1", "lname1", "ABC"));
myObjects.add(new MyObject("fName2", "lname2", "PQR"));
myObjects.add(new MyObject("fName3", "lname3", "XYZ"));
myObjects.add(new MyObject("fName4", "lname4", "DEF"));
Map<String,Integer> map = new HashMap<>();
map.put("XYZ", 1);
map.put("PQR", 2);
map.put("ABC", 3);
map.put("DEF", 4);
Comparator<MyObject> sortByCode = (obj1,obj2)->Integer.compare(map.get(obj1.code), map.get(obj2.code));
System.out.println("Before sorting");
System.out.println(myObjects);
System.out.println("After sorting");
myObjects.sort(sortByCode);
System.out.println(myObjects);
}
You'd need to create your own Comparator for comparing instances of MyObject according to your logic:
Comparator<MyObject> cmp = (o1, o2) ->{
//Implement comparison logic here
//Compare o1 and o2 and return -1,0, or 1 depending on your logic
};
Then given a list such as this:
List<MyObject> listToSort = ...
You can either sort it in-place using the old Collections.sort() function:
Collections.sort(listToSort, cmp);
Or, if you want, using Java 8 streams:
listToSort.stream().sorted(cmp).collect(Collectors.toList()); //Using streams