Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching for a Value in a HashMap

I have a HashMap of the following type: HashMap<LocalDate, ArrayList<String>> which contains values like:

2015-12-26=[John, J.Fox , Barry]
2015-12-24=[Barry, Michael, Martin],
2015-12-20=[McAllister, Barry, Clark]
..............

Now, if I want to search for "Barry" in the HashMap and get the key which is the most recent (in this case Dec 26th), how would I go about doing that?

The .values() method doesn't seem to work as each key has an ArrayList instead of just one element.

like image 682
Durga Swaroop Avatar asked Sep 14 '25 04:09

Durga Swaroop


2 Answers

In java 8 you could use something like this:

Optional<Map.Entry<LocalDate, List<String>>> first = map
            .entrySet()
            .stream()
            .filter(entry -> entry.getValue().contains("Barry"))
            .sorted(Map.Entry.comparingByKey())
            .findFirst();

This get all the entries from the map, filters them based on the value, sort them based on keys and get the first one, if any. You can then use first.ifPresent() method to do whatever you want with the first entry, here i just printing them to the console:

first.ifPresent(entry -> {
            System.out.println(entry);
        });

Maybe this is NOT the most efficient algorithm but sure it works

Update 1: To sort dates from latest to earliest, use this:

sorted(Map.Entry.<LocalDate, List<String>>comparingByKey().reversed())

Update 2: As Andreas said, you can use max instead of sorted which has better asymptotic behavior. In fact, since you just want the latest item, there is no need for sorting entries in order to get it:

Optional<Map.Entry<LocalDate, List<String>>> found = map
                .entrySet()
                .stream()
                .filter(entry -> entry.getValue().contains("Barry"))
                .max(Map.Entry.comparingByKey());
like image 73
Ali Dehghani Avatar answered Sep 16 '25 17:09

Ali Dehghani


Use the map's Entry Set. For example:

HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();

ArrayList<String> list1 = new ArrayList<String>();
ArrayList<String> list2 = new ArrayList<String>();

list1.add("One");
list1.add("Two");
list1.add("Three");

list2.add("Cat");
list2.add("Dog");
list2.add("Fish");

map.put("Numbers", list1);
map.put("Animals", list2);

for(Map.Entry<String, ArrayList<String>> entry : map.entrySet())
{
    if(entry.getValue().contains("Cat"))
        System.out.println("Found Cat in "+entry.getKey());
}

Output: Found Cat in Animals

Essentially, what we are doing is iterating over the map's Entry Set, checking if each value (which we specified is an ArrayList<String>) contains the String we are looking for, and if it does, we print out the key of the current Entry. (Which, in your case, would be your LocalDate.)

like image 42
Mitch Talmadge Avatar answered Sep 16 '25 18:09

Mitch Talmadge