简体   繁体   English

通过使用 lambda 表达式和 Java 从 88677344588 的 ArrayList 中提取 HashMap 8

[英]Extract HashMap from an ArrayList of Hashmap by using lambda expression with Java 8

请在此处检查数据结构图像

I need to find a Hashmap whose is_default value is equal to 1.我需要找到一个 Hashmap,它的 is_default 值等于 1。

Noted: In this structure, only 1 hashmap contains is_default value is equal to 1.注意:在这个结构体中,只有1个hashmap包含is_default值等于1。

You only need to check those maps that contain the required key.您只需要检查那些包含所需密钥的地图。 After that, you need to choose from them the one with the desired value of this key.之后,您需要从中选择具有所需键值的那个。 It can be done with filter可以filter来完成

list.stream()
    .filter(x -> x.containsKey("is_default"))
    .filter(x -> x.get("is_default")
                  .compareTo(BigDecimal.ONE) == 0)
    .forEach(System.out::println);

Or you can use getOrDefault and specify wrong value as default to skip those maps that do not contain a key或者您可以使用getOrDefault并将错误值指定为默认值以跳过那些不包含键的映射

list.stream()
    .filter(x -> x.getOrDefault("is_default", BigDecimal.ZERO)
                  .compareTo(BigDecimal.ONE) == 0)
    .forEach(System.out::println);

Example例子

public static void main(String[] args) {
    List<Map<String, BigDecimal>> list = new ArrayList<>();

    // target
    Map<String, BigDecimal> map = new HashMap<>();
    map.put("is_default", BigDecimal.ONE);
    map.put("key", BigDecimal.TEN);
    list.add(map);

    Map<String, BigDecimal> map2 = new HashMap<>();
    map2.put("is_default", BigDecimal.ZERO);
    map2.put("key", BigDecimal.ZERO);
    list.add(map2);

    Map<String, BigDecimal> map3 = new HashMap<>();
    map3.put("isnt_default", BigDecimal.ZERO);
    list.add(map3);

    list.stream()
        .filter(x -> x.containsKey("is_default"))
        .filter(x -> x.get("is_default")
                      .compareTo(BigDecimal.ONE) == 0)
        .forEach(System.out::println);
}

Output Output

{is_default=1, key=10}

Try this.尝试这个。

public static void main(String[] args) {
    List<Map<String, String>> list = List.of(
        Map.of("is_default", "0", "label", "test0"),
        Map.of("is_default", "1", "label", "test1"),
        Map.of("is_default", "2", "label", "test2"));
    Map<String, String> extracted = list.stream()
        .filter(map -> Objects.equals(map.get("is_default"), "1"))
        .findFirst().orElse(null);
    System.out.println(extracted);
}

output: output:

{label=test1, is_default=1}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM