user2051347
user2051347

Reputation: 1669

Get a sublist of a hashmap

Lets say I have a hashmap with key String and value is also a String. I want to extract for a certain key element range a sublist(like with the sublist function of List) of the values of the map.

How could that be realized?

Upvotes: 1

Views: 7720

Answers (3)

Alexis C.
Alexis C.

Reputation: 93842

As I said in comments, I wouldn't go for an HashMap, but for a SortedMap instead (a TreeMap per example), which have a subMap method :

subMap(K fromKey, K toKey)

Returns a view of the portion of this map whose keys range from fromKey, inclusive, to toKey, exclusive.


SortedMap<String, String> m = new TreeMap<>();
m.put("aaa","1");
m.put("bbb","2");
m.put("ccc","3");
m.put("ddd","4");
m.put("eee","5");

SortedMap<String, String> subM = m.subMap("a","d");
System.out.println(subM);

Output :

{aaa=1, bbb=2, ccc=3}

If you need only the list of the values, use the values() method.

Upvotes: 3

crush
crush

Reputation: 17013

Here's a pretty naive example.

Let's say you have a HashMap that looks like the following:

public Map<Integer, String> map = new HashMap<Integer, String>();

You're saying that you want to create a sublist, so I'll assume you want a List<String> as an output:

public List<String> getKeyRange(Integer start, Integer end) {
    List<String> list = new ArrayList<String>();

    for (int i = start; i < end; i++) {
        String value = map.get(i); //Forgot that string can be null in Java

        if (value != null)
            list.add(value);
    }

    return list;
}

Upvotes: 2

MikeFHay
MikeFHay

Reputation: 9003

<K, V> List<V> getAll(Map<K, V> map, Collection<K> keys)
{
    List<V> values = new ArrayList<V>(keys.size());
    for(K key : keys)
    {
        values.add(map.get(key));
    }
    return values;
}

Upvotes: -1

Related Questions