简体   繁体   中英

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.

Noted: In this structure, only 1 hashmap contains is_default value is equal to 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

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

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

{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:

{label=test1, is_default=1}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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