G. Dawid
G. Dawid

Reputation: 172

How to convert LinkedHasMap Values into ArrayList/Array in right order?

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.

Upvotes: 4

Views: 2569

Answers (3)

Thiam Hooi
Thiam Hooi

Reputation: 121

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.

Upvotes: 0

Andy Turner
Andy Turner

Reputation: 140318

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());

Upvotes: 1

Eran
Eran

Reputation: 393811

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

Upvotes: 4

Related Questions