0

What is the fastest way to get new map using subKeySet of an existing Map?

Example:

existing map is:

1|"one"

2|"two"

3|"three"

KeySet is: 1,2,3

Than I clone this keyset and remove first value: 2,3 What is the fastest way to get this map:

2|"two"

3|"three"

using new keyset

ZuzEL
  • 12,768
  • 8
  • 47
  • 68

2 Answers2

2

Guava has Maps.filterKeys() method specifically for this purpose:

Maps.filterKeys(map, Predicates.in(keys));
endragor
  • 368
  • 2
  • 9
1

You already have it, if you removed the unnecessary key ?

Otherwise, create an entryset loop over, and add the required key/values pairs to your new/other hashmap.

You can also use a sortedmap, or navigablemap which has additonal functionality for filtering a range.

or if using jdk 8 you can uses its uber cool new functioanlity :

m.entrySet().stream()
    .filter(p -> p.getKey() > 1) // or whatever you want
    .collect(toMap(Entry::getKey, Entry::getValue));
NimChimpsky
  • 46,453
  • 60
  • 198
  • 311