Retrieving Objects From Java Collection By List of IDs

Today in the NixMashup Links App I'm building we have a cached list of NixMashup Links from which we want to display only those links that have a certain tag. We're not going to go to the database, but rather will use Java 8 Streams.

Pictures first. Here's a sample list of links displayed for the tag “Streams.”

Collection Selection by List<Integer>

In essence what we're doing is filtering our NixMashupLinks Collection by a List of Link IDs, or all of the link IDs for the selected tag.  We're going to retrieve those IDs from our NixMashupTagLinks Collection in the form of a List<Integer>.

Before we do that, here's a representation of the NixMashupTagLink object from PostgreSQL. We're going to make a List of the link_id field for the selected tag.

Onto the code.

public static List<Integer> getNixMashupTagLinkIds(String tag) {
	return getNixMashupTagLinks()
			.stream()
			.filter(l -> l.tag.equals(tag))
			.map(l -> l.linkId)
			.collect(Collectors.toList());
}

Extracting the NixMashupLink Objects from the Link_ID List

Now for the interesting task of retrieving a subset of NixMashupLink objects. Below is the source on that. As you see we're passing the List<Integer> of Link IDs we just created. Each NixMashupLink has a unique LinkId key which we'll compare to the LinkId list, using a linkIds.contains(nixMashupLink.linkId) test to set a NixMashupLink.hasTag boolean property while iterating through the NixMashupLinks Collection.

With NixMashupLink.hasTag set we can use Java Streams to filter out only those items set to TRUE. As a bonus we'll use a reverseSort Java Comparator “byPostDate” to display the most recent links for the tag first.

public static List<NixMashupLink> getNixMashupTagLinks(List<Integer> linkIds) {
	
	List<NixMashupLink> allNixMashupLinks = getNixMashupLinks();
	for (NixMashupLink nixMashupLink : allNixMashupLinks) {
		nixMashupLink.setHasTag(linkIds.contains(nixMashupLink.linkId));
	}
	
	return allNixMashupLinks
			.stream()
			.filter(l -> l.getHasTag() == true)
			.sorted(byPostDate)
			.collect(Collectors.toList());
}

Damn fine looking Java Code, and no trip to the database.

Posted June 03, 2014 04:03 PM EDT

More Like This Post