I have two lists:
List<String> ids
List<String> names
The task is to create one Map<String,String> out of these two lists, preferably using Java 8.
Unfortunatly, I did not find how to make it when we have lists with String type.
I have two lists:
List<String> ids
List<String> names
The task is to create one Map<String,String> out of these two lists, preferably using Java 8.
Unfortunatly, I did not find how to make it when we have lists with String type.
Assuming both the lists have the same size & ids are unique & ids are the keys of the map and names are corresponding values, you can use the following code to create a map:
Map<String,String> idsNames = IntStream.range(0,ids.size())
.mapToObj(i -> new AbstractMap.SimpleEntry<>(ids.get(i),names.get(i)))
.collect(Collectors.toMap(AbstractMap.SimpleEntry::getKey,
AbstractMap.SimpleEntry::getValue));
Map.Entry for each i. Just using IntStream.range(0,ids.size()).boxed().collect(Collectors.toMap(ids::get, names::get)) should suffice. It's also worth mentioning that this approach works well if both lists are random access, i.e. ArrayList.