Java 8 Streams 哈希图

我需要使用 Java 8 流执行哈希图迭代。我需要遍历一个哈希图。检查特定键(“new”)是否没有空值或空值,将该值复制到字符串类型的变量(字符串 val1)。然后再次检查 ex:"old" 的另一个键,然后将该值复制到 string 类型的变量 (String val2) 并调用 main 方法,我需要发送这两个值 (val1, val2)。这必须在 hashmap 迭代中完成。你能帮我解决这个问题吗?


编码:


map1.entrySet()

    .stream()

    .filter(s -> { 

        if (s.getKey().contains("abc") && !s.getValue().equals("") && s.getValue()!=null) {

            String val1 = s.getValue;

            if (s.getKey().contains("bb")) {

                String val2 = s.getValue(); //call the function

                callFunction(val1,val2);

            }

        }

        else {

        } 

    });


12345678_0001
浏览 109回答 3
3回答

有只小跳蛙

试试这个:yourMap.entrySet().stream()从这一点上,您可以管理。Stream 由 组成,Entry<Key,Value>因此您可以检查任何您想要的内容。

白板的微信

你需要寻找特定的键:new和old这样你就不会需要遍历地图的入口,因为如果存在密钥,他们将是唯一的。获取特定键的值,如果它们不存在,则保持为空 String用这些值做你的事Map<String, String> map1 = ...;String v1 = map1.getOrDefault("new", "");String v2 = map1.getOrDefault("old", "");Map<String, String> map2 = new HashMap<>();if(!v1.isEmpty() && !v2.isEmpty() && validateMethod(v1, v2)){&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; // do your stuff}您可能会将 isEmpty 的检查放在您的validateMethod而不是 if 中

梵蒂冈之花

需要使用 Java 8 完成for(Map.Entry e : map1.entrySet()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(e.containsKey("new")&& !e.getValue().equals("")){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String val1 = (String) e.getValue();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(e.containsKey("old")&& !e.getValue().equals("")){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String val2 = (String) e.getValue();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //call the function-- This is boolean&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(validateMethod(val1, val2)){ // if true&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Map<String, String> map2 = new HashMap<>();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; map2.putAll(e);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java