2

I'm trying to return keys and values through an array method.

I have done this:

public ArrayList<String> translationList() {
    for (String key : translations.keySet()) {
        System.out.println(key + " = ");
    }
    return new ArrayList<String>(this.translations.values());
}

And in my Main.java

ArrayList<String> translations = dictionary.translationList();
for (String translation : translations) {
    System.out.println(translation);
}

It returns

apina = 
cembalo = 
banaani = 
monkey
harpsichord
banana

I'm not sure how to get them to print on the same line after the translation of the word. I know it's printing the for loop before returning the array but that is where my problem is and not sure how to solve it.

1
  • use System.out.println("translations="+translations); or inside for-loop use `System.out.print(translation); Commented Sep 20, 2015 at 5:31

1 Answer 1

3

Since you are getting only values back there is no way to get key based on value. So hence not possible.

What you can do is return keys from method and iterate that in your method.

or simply change your method to

public ArrayList<String> translationList() {
    List<String> returnList = new ArrayList<>(String);
    for (Entry<Integer, String> entry : testMap.entrySet()) {

                returnList.add(entry.getKey()+"="+entry.getValue());

        }
    return returnList;
}

and in your main method

ArrayList<String> translations = dictionary.translationList();
for (String translation : translations) {
    System.out.println(translation);
}
Sign up to request clarification or add additional context in comments.

3 Comments

I understand but I'm not sure how I could do that, could you explain a bit more?
Okay I see, the website I'm doing exercises on hasn't taught me about getKey or getValue so I didn't know to use them. Would there be no other way to do this? Thank you for your help
@syntax This is the way I know.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.