Programming-Idioms

History of Idiom 28 > diff from v1 to v2

Edit summary for version 2 :

Version 1

2015-04-07, 14:06:52

Version 2

2015-04-07, 14:07:21

Idiom #28 Sort by a property

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

Idiom #28 Sort by a property

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

Imports
import java.util.Arrays;
import java.util.Comparator;
Imports
import java.util.Arrays;
import java.util.Comparator;
Code
Arrays.sort(items, new Comparator<Item>(){
	public int compare(Item a, Item b){
		return a.birth - b.birth;
	}
});
Code
Arrays.sort(items, new Comparator<Item>(){
	public int compare(Item a, Item b){
		return a.birth - b.birth;
	}
});
Comments bubble
items is a Item[].
Use an anonymous class which implements Comparator<Item>
Comments bubble
items is an array of type Item[].
Use an anonymous class which implements Comparator<Item>
Demo URL
http://ideone.com/gqNVEH
Demo URL
http://ideone.com/gqNVEH