非常感谢您的所有回答/评论!
对我在原始问题中放入的错误代码示例表示歉意。我试图简化我的问题,但显然它最终变得相当困惑。
我稍微改变了代码:
Map<String, Boolean> map1 = new HashMap<>();
map1.put("Yes", Boolean.FALSE);
map1.put("No", Boolean.FALSE);
Map<String, Map<String, List<String>>> map2 = new HashMap<>();
List<String> list1 = Arrays.asList("Apple", "Peach");
List<String> list2 = Arrays.asList("Pear", "Orange");
Map<String, List<String>> innerMap = new HashMap<>();
innerMap.put("fruit1", list1);
innerMap.put("fruit2", list2);
map2.put("Fruits", innerMap);
map2.put("Vege", new HashMap<>());
Optional<? extends Entry<String, ? extends Object>> optional = Stream
.of(map1.entrySet().stream().filter(e -> e.getValue()).findFirst(),
map2.entrySet().stream().filter(entry -> entry.getValue().entrySet()
.stream()
.anyMatch(e -> e.getKey().equals("Fruit") && e.getValue().stream().anyMatch(
i -> i.equals("Pear"))))
.findFirst())
.filter(Optional::isPresent).map(Optional::get).findFirst();
optional.orElse(new AbstractMap.SimpleEntry<>("NULL", null));
我遇到第一个错误:
Cannot infer type arguments for AbstractMap.SimpleEntry<>
所以我将最后一行更改为:
optional.orElse(new AbstractMap.SimpleEntry<String, Object>("NULL", null));
然后 orElse 上弹出一个新错误:
The method orElse(capture#4-of ? extends Map.Entry) in the type Optional> is not applicable for the arguments (AbstractMap.SimpleEntry)
据我了解,两个 Map 具有相同的 Key 类型但不同的 Value 类型。每个 map 的过滤器也不同。因此返回的将是一个可选的,带有一个字符串类型Key的条目,但一个泛型类型值。
我最初的问题是我不知道如何为此Optional提供默认值,因为Entry的值类型是通用的(我现在仍然不知道答案)。
受@Ole的启发,我重构了代码,如下所示:
String result = Stream
.of(map1.entrySet().stream().filter(e -> e.getValue()).map(Map.Entry::getKey).findFirst(), map2
.entrySet().stream().filter(entry -> entry.getValue().entrySet()
.stream()
.anyMatch(e -> e.getKey().contains("fruit") && e.getValue().stream().anyMatch(
i -> i.equals("Pear"))))
.map(Map.Entry::getKey)
.findFirst())
.filter(Optional::isPresent).map(Optional::get).findFirst().orElse("NULL");
System.out.println("result: " + result);
虽然我只将过滤后的条目 key 收集到流中,但 JAVA 编译器似乎运行良好。我得到的执行结果为
result: Fruits
但看来我还是把事情复杂化了......
最佳答案
Map.Entry<String, ?> result = Stream.of(map1, map2)
.flatMap(m -> m.entrySet().stream())
.filter(e -> e.getKey().equals("Yes"))
.findFirst()
.orElse(new AbstractMap.SimpleEntry<>("NULL", null));
System.out.println(result);
输出:
NULL=null
您对Optional
的处理过于复杂化了。来自findFirst
。不要使用isPresent
也不get
, orElse
为您做一切。
您也不需要 AbstractMap.SimpleEntry
的类型参数。 Java 推断 <String, Object>
从参数("NULL", null)
.
我发现从 map 流开始更容易,因此我们只需要指定一次我们正在使用 map 做什么。
顺便说一句,您的每张 map 仅包含一个条目。你的第二个put
操作具有相同的 key ,因此会覆盖第一个 put
中放入的条目称呼。因此,当省略第一个调用时,您可以获得相同的结果。
关于java - 如何为 JAVA 中的泛型类型提供默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57079626/