Programming-Idioms

History of Idiom 28 > diff from v33 to v34

Edit summary for version 34 :
[Java] Property name is p. +DocURL

Version 33

Version 34

Idiom #28 Sort by a property

Sort elements of array-like collection items in ascending order of x.p, where p is a field of the type Item of the objects in items.

Idiom #28 Sort by a property

Sort elements of array-like collection items in ascending order of x.p, where p is a field of the type Item of the objects in items.

Imports
import java.util.Collections;
import java.util.Comparator;
Imports
import java.util.Collections;
import java.util.Comparator;
Code
Collections.sort(items, new Comparator<Item>(){
	public int compare(Item a, Item b){
		return a.birth - b.birth;
	}
});
Code
Collections.sort(items, new Comparator<Item>(){
	@Override
	public int compare(Item a, Item b){
		return a.p - b.p;
	}
});
Comments bubble
items is a List<Item>.
Use an anonymous class which implements Comparator<Item>
Comments bubble
items is a List<Item>.
Use an anonymous class which implements Comparator<Item>.
Doc URL
https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html