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.

Dave
  • 5,108
  • 16
  • 30
  • 40
G. Dawid
  • 162
  • 1
  • 11
  • call `list.add(value)` on the list? or not? – UninformedUser May 29 '19 at 06: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. – Andy Turner May 29 '19 at 06: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`. – Stephen C May 29 '19 at 06:27

3 Answers3

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>.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • My original map is in Course class, and it's `private LinkedHashMap> grades;` It's to store student grades, so it contains Student object and grades as ArrayList, that he have. – G. Dawid May 29 '19 at 17:25
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());
Lino
  • 19,604
  • 6
  • 47
  • 65
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • 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. – Lino May 29 '19 at 07:03
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.

Thiam Hooi
  • 111
  • 2
  • 8