4

I'm getting LinkedHashMap grades = courses.get(choise).getGrades();

I need to save the grades values in an array/arraylist.

I'm able to get values and keys in loop

String key = "";
String value = "";
for (Object o : grades.keySet()){
  key = o.toString();
  value = grades.get(o).toString();
}

And print it like so

System.out.println("Grades: " + value);

Example output is

Grades:[0, 3, 2, 5, 3]

My goal is to have each grade separated in an array/list.

3
  • call list.add(value) on the list? or not? Commented May 29, 2019 at 6:18
  • Note that you don't have to iterate the key set to get the values: you can iterate grades.entrySet() if you want both key and value together, or grades.values() if you just want the values. Commented May 29, 2019 at 6:23
  • I'm afraid that since you do state clearly what you mean by "the right order", we can only guess that "the right order" is the insertion order for the entries of the LinkedHashMap. Commented May 29, 2019 at 6:27

3 Answers 3

4

You don't have to worry about the order. Whether you obtain the values() or keySet() or entrySet() from the LinkedHashMap, the iteration order of any of them would be according to the insertion order into the LinkedHashMap.

Putting the values in a List is as simple as:

List<SomeType> grades = new ArrayList<>(grades.values());

Of course, for that to work you have to change LinkedHashMap grades to LinkedHashMap grades<KeyType,SomeType>.

Sign up to request clarification or add additional context in comments.

1 Comment

My original map is in Course class, and it's private LinkedHashMap<Student, ArrayList<Integer>> grades; It's to store student grades, so it contains Student object and grades as ArrayList, that he have.
1

The first thing you have to sort out, is the raw type:

LinkedHashMap grades = courses.get(choise).getGrades();

You need the generic type on the variable type, even if you just use ?:

LinkedHashMap<?, ?> grades = courses.get(choise).getGrades();

but if you know a more specific type than ?, you can use that - it looks from the question like your keys at least are Strings.

Then:

List<String> list = 
    grades.values().stream()
        .map(Object::toString)
        .collect(Collectors.toList());

1 Comment

If my edit did conflict with your intents then I am very sorry and feel free to revert it, but it just sounded very weird for me.
0

Found solution from a website.

The below codes does the trick if provided that grades is a LinkedHashMap<String, String>.

String[] arrayGrades = grades.keySet().toArray(new String[0]);

The code was tested wthin JavaVersion.VERSION_1_8 environment.

Comments

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.