Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get List value from map object

Tags:

java

list

hashmap

I have object value called "mastervalue" from my hashmap. The mastervalue contain ques_id as key, and an array contain score and answer as value. How to get value of the array only(the score and answer) and return as List.

String maprule = "department == '2' && topic == '1'";

mastervalue = (Map<String, List<String>>) map_master.get(maprule);
System.out.println(mastervalue);

mastervalue print out : {10359=[4, 1], 10365=[1, 1], 10364=[1, 1], 10363=[4, 1], 10362=[3, 1], 10369=[1, 1], 10368=[5, 1]}

like image 838
Miss_Ann Avatar asked Nov 28 '22 07:11

Miss_Ann


1 Answers

Okay:

public <T> List<T> getValues(Map<?, T> map) {
    return new ArrayList<>(map.values());
}

Inlined:

List<List<String>> list = new ArrayList<>(map_master.values());

Or using the method:

List<List<String>> list = getValues(map_master);

Alternatively, if you want to put all the values of all the lists into one, just iterate:

List<String> total = new ArrayList<>();
for (List<String> lis : map_master.values()) {
    total.addAll(lis);
}

And with Java 8 streams:

List<String> total = map_master.values().stream()
                            .flatMap(Collection::stream)
                            .collect(Collectors.toList());
like image 126
Rogue Avatar answered Dec 05 '22 15:12

Rogue