使用Java 8流处理地图列表

use*_*260 6 java lambda java-stream

如何将此代码简化为单个lambda表达式?我的想法是有一个地图列表,我想创建一个新的地图列表,使用密钥过滤器.在这个例子中,我想重新映射它,使它只保留键"x"和"z".

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

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

    List<Map> l = new ArrayList<>(Arrays.asList(m0, m1));
    List<Map> tx = new ArrayList<>();
    for(Map<String, String> m : l) {
        Map<String, String> filtered = m.entrySet()
                .stream()
                .filter(map -> map.getKey().equals("x") || map.getKey().equals("z"))
                .collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));
        tx.add(filtered);
    }
    System.err.println("l: " + l);
    System.err.println("tx: " + tx);
Run Code Online (Sandbox Code Playgroud)

输出:

    l: [{x=123, y=456, z=789}, {x=000, y=111, z=222}]
    tx: [{x=123, z=789}, {x=000, z=222}]
Run Code Online (Sandbox Code Playgroud)

Hol*_*ger 12

当然,您可以将整个操作转换为一个Stream操作.

// no need to copy a List (result of Array.asList) to an ArrayList, by the way
List<Map<String, String>> l = Arrays.asList(m0, m1);

List<Map<String, String>> tx = l.stream().map(m -> m.entrySet().stream()
        .filter(map -> map.getKey().equals("x") || map.getKey().equals("z"))
        .collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue())))
    .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

但请注意,流式传输Map和过滤是一种具有线性时间复杂度的操作,因为它会根据过滤器检查每个地图的每个键,而您只需要保留非常少量的实际键.所以在这里,使用它会更简单,更有效(对于更大的地图)

List<Map<String, String>> tx = l.stream()
    .map(m -> Stream.of("x", "y")
                    .filter(m::containsKey).collect(Collectors.toMap(key->key, m::get)))
    .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

每个地图只执行四次查找.如果它困扰你,你甚至可以将它减少到两次查找,但是,常数因素与整体时间复杂度无关,如果地图具有恒定的时间查找,则这将是恒定的时间HashMap.即使对于具有O(log(n))查找时间复杂度TreeMap的地图,如果地图大于示例代码的三个映射,这将比线性扫描更有效.


Jac*_* G. 5

您可以尝试如下操作:

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

l.forEach(map -> {
    map.entrySet().removeIf(e -> !e.getKey().equals("x") && !e.getKey().equals("z"));
});
Run Code Online (Sandbox Code Playgroud)

Map<String, String>如果输入键不是x或,它将简单地删除每个映射中的所有映射z

编辑:您应该使用Radiodef的等效方法,但是方法更短!

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

l.forEach(map -> map.keySet().retainAll(Arrays.asList("x", "z"));
Run Code Online (Sandbox Code Playgroud)