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.
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());
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
.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With