Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating subset of HashMap based on some specifications?

Tags:

java

hashmap

So I have the following HashMap:

HashMap<String, List<someDataType>> map;

I want to create a new HashMap that is only composed of the k/v pairs in map that have a value (the list) whose length is less than a certain "x". The only way I know how to do this is to iterate through the HashMap and put k/v pairs into a new HashMap. Is there a more concise way to achieve what I'm looking for? Thanks.

like image 874
r123454321 Avatar asked Jun 26 '13 21:06

r123454321


People also ask

What is the strategy for designing key of a HashMap?

If you want to make a mutable object as a key in the hashmap, then you have to make sure that the state change for the key object does not change the hashcode of the object. This can be done by overriding the hashCode() method. But, you must make sure you are honoring the contract with equals() also.

Can one key have multiple values in HashMap?

A standard Java HashMap cannot store multiple values per key, any new entry you add will overwrite the previous one. Save this answer.

Does HashMap size affects the performance of HashMap?

An instance of HashMap has two parameters that affect its performance: initial capacity and load factor. The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created.

How do you create a Submap in Java?

Use retainAll() Method retainAll(keyList); Note that this method will edit the original map. If we don't want to affect the original map, we can create a new map first using a copy constructor of HashMap: Map<Integer, String> newMap = new HashMap<>(map); newMap.


1 Answers

Using guava:

Map<String, List<String>> newMap = 
    Maps.filterEntries(originalMap, new MyEntryPredicate(10));

where:

private static class MyEntryPredicate implements Predicate<Map.Entry<String, List<String>>> {

    // max list length, exclusive
    private int maxLength;

    private MyEntryPredicate(int maxLength) {
        this.maxLength = maxLength;
    }

    @Override
    public boolean apply(Map.Entry<String, List<String>> input) {
        return input != null && input.getValue().size() < maxLength;
    }
}
like image 63
Keith Avatar answered Sep 27 '22 20:09

Keith