Reputation: 593
I have ImmutableMap<String, Integer>
and List<String>
that defines the order. I want to get ImmutableList<Integer>
with that order. For example:
map (<"a", 66>, <"kk", 2>, <"m", 8>)
list ["kk", "m", "a"]
As result I want another list of values from given list with defined order :[2, 8, 66].
What is the best way to do it in java?
Upvotes: 0
Views: 918
Reputation: 10703
Try this,
List<Integer> numbers= new ArrayList<>(map.size());
for(String l : list) {
numbers.add(map.get(l));
}
example from Java 8 streams
List<Integer> numbers= list.stream().map(map::get).collect(Collectors.toList());
Java SE 8 to the rescue! The Java API comes with a new abstraction called Stream that lets you process data in a declarative way. Streams can leverage multi-core architectures without you having to write a single line of multithread code.
Upvotes: 1
Reputation: 1933
Without streams you can use a simple for loop:
List<Integer> valuesInOrder = new ArrayList<>(map.size());
for(String s : list) {
valuesInOrder.add(map.get(s));
}
If you want to use streams you could do:
List<Integer> valuesInOrder =
list.stream().map(map::get).collect(Collectors.toList());
Upvotes: 5