Durga Swaroop Durga Swaroop - 4 years ago 128
Java Question

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.

Answer Source

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());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download