Reverse Order Collection Sorting With Java Streams

A quick example on reverse sorting a collection using Java Streams. As you'll see, it's very slick and is done with very few lines of code.

For a bit of context, the NixMashupLink objects in the code example are the individual links from my NixMashup Posts which we will display chronologically, with the most recent displayed first, your typical “recent posts” collection.

The two-step process for generating our reverse sorted collection is to 1) create our reverseOrder Object Comparator, then 2) use that Comparator in our Stream sorted() method.

public static List<NixMashupLink> getMostRecentNixMashupLinks() {

	// @formatter:off
	
	Comparator<NixMashupLink> byPostDate = 
			Collections.reverseOrder(Comparator.comparing(NixMashupLink::getLinkDatetime));
	
	List<NixMashupLink> nixMashupLinks = getNixMashupLinks()
			.stream()
			.sorted(byPostDate)
			.collect(Collectors.toList());
	
	// @formatter:on

	return nixMashupLinks;
}

I told you it required very few lines of code…

Posted May 31, 2014 09:19 AM EDT

More Like This Post