2

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?

Tukaram Bhosale
  • 348
  • 3
  • 17
  • 1
    Possible duplicate of [Java: How to convert List to Map](https://stackoverflow.com/questions/4138364/java-how-to-convert-list-to-map) – Yassin Hajaj Jun 10 '18 at 19:37
  • Might want to include some sample data - this isn't very easy to understand as-is. – user681574 Jun 10 '18 at 19:37
  • 2
    Would be great if you can provide an example. So question already might have been answered and this question might be duplicated. – dbustosp Jun 10 '18 at 19:40
  • 1
    In this case I'd advice the good old `Iterator`. With Java 8 streams you can access a single element of your list, not two as you need. At least, not without creating some overly complex construct. – M. le Rutte Jun 10 '18 at 19:46

1 Answers1

4

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.

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
  • @ZhekaKozlov Nope... the OP clearly said _"I am getting result in List of List format which I will process to get a Map."_. maybe they don't have the right to change the type of result they're getting. I believe the example in the post was just to simplify things and better illustrate the description of the post. if one were to use your solution it would be problematic as 1) you don't know the size of the result beforehand , 2) you have to manually put each pair in the map. – Ousmane D. Jun 11 '18 at 09:52
  • @ZhekaKozlov Anyhow, ultimately I am solving a question which was asked and that is " how to take a `List>` and turn it into a `Map`". Nothing more. Nothing less. – Ousmane D. Jun 11 '18 at 09:55
  • You are right. My solution was for `List` rather than `List>`. I deleted it. – ZhekaKozlov Jun 11 '18 at 10:50