Reputation: 89
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]}
Upvotes: 4
Views: 66550
Reputation: 4599
For Kotlin there is a shortcut:
map.values.flatten()
As the doc states:
Returns a single list of all elements from all collections in the given collection.
Upvotes: 0
Reputation: 21561
For Koltin users here is the way:
val listOfObjects = List<Object>?.stream()?.flatMap { obj: Collection<Object> -> obj.stream() }
?.collect(Collectors.toList())
Generic way:
fun <T: Any> listList(list: List<List<KClass<T>>>) = list.stream().flatMap { obj: Collection<*> -> obj.stream() }.collect(Collectors.toList())
Upvotes: 0
Reputation: 11483
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());
Upvotes: 25