Tukaram Bhosale
Tukaram Bhosale

Reputation: 368

convert List<Object> to Map<K,V> in java

I am getting result in List of List format which I will process to get a Map. Twist is that inner list will contain 2 different type of objects. Object of type K will be on index 0 and another object of type V will be on index 1.

List<Object> lst = new ArrayList<>();
lst.add(new KeyObject());  
lst.add(new ValueObject()); 

List<List> res = new ArrayList<>();
res.add(lst); 

Now I want to construct a Map< K, V> from above res List using java 8 approach. Any suggestions?

Upvotes: 2

Views: 1440

Answers (1)

Ousmane D.
Ousmane D.

Reputation: 56393

Assuming res is a type List<List<Object>> as you've mentioned, here is how you can get the result you're after:

Map<K, V> result = 
          res.stream()
             .collect(Collectors.toMap(e -> (K)e.get(0), e -> (V)e.get(1)));

Where K is the actual type of your keys and V is the actual type of the values.

Upvotes: 4

Related Questions