Java8 convert List of Map to List of string

VelNaga :

I am using Java8 to achieve the below things,

 Map<String, String> m0 = new HashMap<>();
        m0.put("x", "123");
        m0.put("y", "456");
        m0.put("z", "789");

        Map<String, String> m1 = new HashMap<>();
        m1.put("x", "000");
        m1.put("y", "111");
        m1.put("z", "222");

        List<Map<String, String>> l = new ArrayList<>(Arrays.asList(m0, m1));

        List<String> desiredKeys = Lists.newArrayList("x");

        List<Map<String, String>> transformed = l.stream().map(map -> map.entrySet().stream()
                .filter(e -> desiredKeys.stream().anyMatch(k -> k.equals(e.getKey())))
                .collect(Collectors.toMap(e -> e.getKey(), p -> p.getValue())))
                .filter(m -> !m.isEmpty())
                .collect(Collectors.toList());
        System.err.println(l);
        System.err.println(transformed);
        List<String> values = new ArrayList<>();
        for (Map<String,String> map : transformed) {
            values.add(map.values().toString());
            System.out.println("Values inside map::"+map.values());
        }
        System.out.println("values::"+values); //values::[[123], [000]]

Here, I would like to fetch only the x-values from the list. I have achieved it but it is not in a proper format.

Expected output: values::[123, 000]

Actual output: values::[[123], [000]]

I know how to fix the actual output. But is there any easy way to achieve this issue? Any help would be appreciable.

Misha :

You do not need to iterate over the entire map to find an entry by its key. That's what Map.get is for. To flatten the list of list of values, use flatMap:

import static java.util.stream.Collectors.toList;
.....

List<String> values = l.stream()
    .flatMap(x -> desiredKeys.stream()
            .filter(x::containsKey)
            .map(x::get)
    ).collect(toList());

On a side note, avoid using l (lower case L) as a variable name. It looks too much like the number 1.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=111146&siteId=1