DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Upender has posted 7 posts at DZone. View Full User Profile

Find An Element from Map and Map contains values as List using Guava

  • submit to reddit
public class FindItemFromMap
public static void main(String args[])
Map<String,List<String>> map = new HashMap<>();
		List<String> fruits = Arrays.asList("apple","orange","banana");
		List<String> juice=   Arrays.asList("pepsi","fanta","sprite");
		map.put("juice", juice);
		String result = Iterables.find(Iterables.concat(map.values()), new Predicate<String>()
		public boolean apply(@Nullable String input) {
			return "banana".equals(input);
	}) ;
	System.out.println("Found "+result);

Finding an element from Map bit  complex but using Google Guava API its simply whole logic. The above code explain how can f we ind an element from MAP object and it contains list of objects.

Iterables.concat() method collect lists and combine into single list.

Iterables.find() method find an element from the list by specified Predicate