0

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

Firoz Memon
  • 4,282
  • 3
  • 22
  • 32

2 Answers2

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));
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