从Stream <T>收集HashMap <String,Object>

时间:2019-11-07 09:50:12

标签: java

使用键的Map进行迭代,并根据返回HashMap的条件,需要在代码下方收集返回图。

尝试在Java 8中转换以下Java代码

 for (String key :  sectionsJson.keySet()) {
            Map<String, Object> section = (Map<String, Object>) sectionsJson.get(key);
            if (index == (Integer) section.get(SECTION_FIELD_KEY_INDEX)) {
                section.put(SECTION_FIELD_KEY_SECTION_KEY, key);
                return section;
            }
        }

任何建议。

3 个答案:

答案 0 :(得分:1)

您似乎想生成一个最多只有一个条目的Map

Map<String,Object> map = 
    sectionsJson.entrySet()
                .stream()
                .filter(e -> {
                    Map<String, Object> section  = e.getValue ();
                    return index == (Integer) section.get(SECTION_FIELD_KEY_INDEX);
                }
                .map(e -> new SimpleEntry<> (SECTION_FIELD_KEY_SECTION_KEY, e.getKey ()))
                .limit(1)
                .collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue));

您的原始代码看起来更简单。

也许您可以简单地搜索所需的键:

String value =
    sectionsJson.entrySet()
                .stream()
                .filter(e -> {
                    Map<String, Object> section  = e.getValue ();
                    return index == (Integer) section.get(SECTION_FIELD_KEY_INDEX);
                }
                .map(Map.Entry::getKey)
                .findFirst()
                .orElse(null);

由于您生成的Map具有(最多)一个值和一个常量键,因此该值是Stream管道应搜索的唯一数据。

答案 1 :(得分:0)

根据您现有的代码。找到匹配项后,您将立即返回地图。您也可以使用Java 8做同样的事情。

  Optional<Integer> findAny = sectionsJson.keySet().stream().filter(key -> {
        Map<String, Object> section = (Map<String, Object>)sectionsJson.get(key);
        if (index == (Integer)section.get("SECTION_FIELD_KEY_INDEX")) {
            section.put("SECTION_FIELD_KEY_SECTION_KEY", key);
            return true;
        }
        return false;

    }).findFirst();
    if (findAny.isPresent()) {
        System.out.println(sectionsJson.get(findAny.get()));
    }

答案 2 :(得分:0)

根据您要实现的目标,可能也是可行的解决方案:

简化循环

for (Map.Entry<String, Map<String, Object>> entry : sectionsJson.entrySet()) {
    Map<String, Object> section = entry.getValue();
    if (index == section.get(SECTION_FIELD_KEY_INDEX)) {
        section.put(SECTION_FIELD_KEY_SECTION_KEY, entry.getKey());
        return section;
    }
}
// add the code for the case when no section was found

分离流处理和变异元素

// find the section
Optional<Map.Entry<String, Map<String, Object>>> first = sectionsJson.entrySet().stream()
        .filter(e -> (Integer) e.getValue().get(SECTION_FIELD_KEY_INDEX) == index)
        .findFirst();
// mutate the section
if (first.isPresent()) {
    Map.Entry<String, Map<String, Object>> sectionJson = first.get();
    sectionJson.getValue().put(SECTION_FIELD_KEY_SECTION_KEY, sectionJson.getKey());
    return sectionJson.getValue();
}
// add the code for the case when no section was found