Betafish
Betafish

Reputation: 1262

Intersection List between HashMap keys and a given list

Its a simple problem. I have a HashMap of String and Double. This is a toy example.

HashMap<String, Double> hm = new HashMap<String, Double>();
hm.put("a", 2.0);
hm.put("b", 4.0);
hm.put("c", 1.0);
hm.put("d", 3.0);

If I have a list tokensList which is for e.g. [b,d]. Can, I get a list which is an intersection of between the elements of list and keys of hashmap.

What I have tried works. But, is there a built in functionality which I'm missing.

List<String> newList = new ArrayList<String>();
for (String word : tokensList) {
    if (hm.containsKey(word.trim())) {
        newList.add(word);
    }
}

Upvotes: 2

Views: 275

Answers (2)

Eritrean
Eritrean

Reputation: 16498

You could use List::retainAll.

List<String> newList  = new ArrayList<>(hm.keySet());
newList.retainAll(tokensList);

Upvotes: 4

RobOhRob
RobOhRob

Reputation: 585

Stream the keyset of the map, add a filter to only include values that are in hm2, then collect to a list. Java streams come very in handy.

HashMap<String,Double> hm = new HashMap<String,Double>();
hm.put( "a", 2.0 );
hm.put( "b", 4.0 );
hm.put( "c", 1.0 );
hm.put( "d", 3.0 );

List<String> hm2 = Arrays.asList( "b", "d" );

List<String> intersection = 
        hm
        .keySet()                               // Fetch all the keys in the map.
        .stream()                               // Make a stream of those keys.
        .filter( key -> hm2.contains( key ) )   // Ignore keys not found in the list.
        .collect( Collectors.toList() );        // Collect the filtered items into a list.

System.out.println( intersection );

Upvotes: 2

Related Questions