Saphire
Saphire

Reputation: 1930

How to browse through a SortedMap?

I have a SortedMap<String, SortedMap<String, Integer>>. where each string is a question with possible answers and points attached.

How can I use this Map to print questions (first one, second one, ...) by their positions like sampleArray[0]?

Upvotes: 5

Views: 9870

Answers (3)

Julian
Julian

Reputation: 1675

One way you can iterate through your map is:

for (String aQuestion : myMap.keySet()) {
    System.out.println(aQuestion)); //Prints each question.  
    System.out.println(myMap.get(aQuestion)); //Prints each answer using the same for loop
}

Alternatively to get the answers you can do:

myMap.values();

This gets a Collection with all the values, or answers in your case. Collection has a method toArray() which will return an ordinary array for easy iteration. But you can also use ArrayList's addAll(Collection c) method to make an arraylist too.

List<String> myAnswers = new ArrayList<>();
myAnswers.addAll(myMap.values());

Upvotes: 4

T.G
T.G

Reputation: 1921

    for (Entry<String, SortedMap<String, Integer>> q : test.entrySet()) {
        System.out.println("Question=" + q.getKey());
        for (Entry<String, Integer> a : q.getValue().entrySet()) {
            System.out.println("Answer: " + a.getKey() + " for points " + a.getValue());

        }
    }

or if you're usin java8

    test.entrySet().stream().forEach((q) -> {
        System.out.println("Question=" + q.getKey());
        q.getValue().entrySet().stream().forEach((a) -> {
            System.out.println("Answer: " + a.getKey() + " for points " + a.getValue());
        });
    });

Btw, when you describing types, use interfaces/abstract classes if possible for example

Map<String, Map<String, Integer>> test;

not

SortedMap<String, SortedMap<String, Integer>> test;

Upvotes: 3

Yaroslav Skudarnov
Yaroslav Skudarnov

Reputation: 165

Just like with usual map, you can iterate over key set:

SortedMap<String, SortedMap<String, Integer>> questions;

//some processing

for (String question : questions.keySet()) {
    System.out.println(question);
}

Upvotes: 2

Related Questions