is there any way to convert Java List to Map in Java 8? I have a List which I want to add the contents to Map
Asked
Active
Viewed 141 times
0
-
There are many ways. Details depend on how the elements of the list are supposed to relate to the entries in the map. – John Bollinger Nov 24 '17 at 05:28
2 Answers
2
Assume the class SomeType has a constructor and two fields named id and name
List<SomeType> list = new ArrayList<>();
list.add(new SomeType(1, "a"));
list.add(new SomeType(2, "b"));
list.add(new SomeType(3, "c"));
Map<Integer, String> result = list.stream().collect(
Collectors.toMap(SomeType::getId, SomeType::getName));

Türkmen Mustafa Demirci
- 333
- 5
- 13
0
I am assuming you have created a List named slist and a Map named map which is initialized from HashMap To create a map from list you need to run a for loop on the list.
for(String skey: slist){
map.put(skey,yourLongValue); //Enter any Long value you desire or create a method which gets value dynamically like getLongValue()
}

Harsh
- 372
- 2
- 15