3

I am trying to get the Get only the key values from the List of Map object using the stream in java 8.

When I stream the List of map object I am getting Stream<List<String>> instead of List<String>.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StreamTest {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    System.out.println("Hello World");
    Map<String, String> a = new HashMap<String, String>();
    a.put("1", "Bharathi");
    a.put("2", "Test");
    a.put("3", "Hello");
    List<Map<String, String>> b = new ArrayList<>();
    b.add(a);
    System.out.println("Hello World" + b);

    /*
     * b.stream().map(c-> c.entrySet().stream().collect( Collectors.toMap(entry ->
     * entry.getKey(), entry -> entry.getValue())));
     */

    Stream<List<String>> map2 = b.stream()
            .map(c -> c.entrySet().stream().map(map -> map.getKey()).collect(Collectors.toList()));
    //List<List<String>> collect = map2.map(v -> v).collect(Collectors.toList());

  }

}

How to get the key object from the List of Map object?

4 Answers 4

6

you can use flatMap over the keySet of each Map within:

List<String> output = lst.stream()
            .flatMap(mp -> mp.keySet().stream())
            .collect(Collectors.toList());
Sign up to request clarification or add additional context in comments.

1 Comment

Aside: There is not much benefit that you get from modeling the objects as List<Map<String, String>> instead of a custom class and then further using a List<CustomClass>.
1

You can simply flatMap it:

b.stream().flatMap(m -> m.keySet().stream()).collect(Collectors.toList())

Comments

1

Of course flatMap is stream base solution! however you can do it with non-stream version in simple way.

List<String> map2 = new ArrayList<>();
b.forEach(map -> map2.addAll(map.keySet()));

Comments

0

You also can use a slightly more declarative way:

List<String> collect = b.stream()
                .map(Map::keySet) // map maps to key sets
                .flatMap(Collection::stream) // union all key sets to the one stream
                .collect(Collectors.toList()); // collect the stream to a new list

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.