0

I have a TreeMap<Token, ArrayList<Token>> and I want to iterate through the map until a specific key which fulfills a requirement. I know that the following works for getting the values of a map:

Collection c = bigrams.values();
Iterator itr = c.iterator();

while (itr.hasNext()){
    System.out.println(itr.next());

However, I want to be able to iterate through the map with the keys linked to the iterator, and check each value based on its pair key. Since bigrams.values() retrieves the value of each of the elements of the bigram, how may I change this to retrieve the keys instead of the values?

2 Answers 2

0

Your question is a bit cryptic, but if you want to get the keys, you can simply use the keySet() method:

Collection c = test.keySet();

If you want to iterate through the map based on the keys, you can do:

for (Token key: bigrams.keySet()) {
    ArrayList<Token> list = bigrams.get(key);
    // do with the list what you want to do with it
}
Sign up to request clarification or add additional context in comments.

Comments

0

You should eilter use Map.keySet() or Map.entrySet():

Map.keySet() returns a set containing all keys of your map. You then can use Map.get() to get the value for a given key:

for (Token key: bigrams.keySet()) {
    List<Token> list = bigrams.get(key);
    System.out.println(key + ": " + list);
}

Map.entrySet() returns a set of all pairs in your map, so there is no need to use Map.get() with this:

for (Map.Entry<Token, List<Token>> entry : bigrams.entrySet()) {
    System.out.println(entry.getKey() + ": " + entry.getValue());
}

Finally you also can use the Java Stream API for this. You also can use it to filter the content very easily. For example to find all tokens containing a given token in their value list:

bigrams.entrySet().stream()
        .filter(e -> e.getValue().contains(tokenToFind))
        .forEach(e -> System.out.println(e.getKey() + ": " + e.getValue()));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.