猿问

将 java 1.8 转换为 1.6

如何将其转换为 java 1.6?方法 .stream() 在 java 1.6 中无法使用。

final Optional<Entry<String, String>> mapping = cfg.getTypeMapping()
                .entrySet()
                .stream()
                .filter(e -> e.getKey().startsWith(jsonType + "|"))
                .findFirst();


慕盖茨4494581
浏览 176回答 2
2回答

收到一只叮咚

让我们快速浏览一下:mapping = cfg.getTypeMapping()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .entrySet()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .filter(e -> e.getKey().startsWith(jsonType + "|"))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .findFirst();上面的代码可能会获取某种映射,获取它的条目,然后迭代它们,以停止在startsWith(jsonType + "|").仅此而已,并且可以很容易地用老式循环代码重写。但这里的实际挑战是::final Optional<Entry<String, String>>类Optional是在 Java 1.8 中添加到 Java 中的。它没有等价物。所以你的整个代码根本无法为 Java 1.6 重写您可以做的最接近的事情:编写该循环代码,如果循环找到某些内容,则返回该结果,否则返回 null。或者,您可以这样做:List<Entry<String, String>> firstMapping = Collections.emptyList();&nbsp;for (Entry<String, String> entries = cfg.getTypeMapping().entrySet()) {&nbsp; if (entry.getKey().startsWith(jsonType + "|")) {&nbsp; &nbsp; firstMapping = Collections.singletonList(entry);&nbsp; &nbsp; break;&nbsp; }}&nbsp;return firstMapping;或者,鉴于 OP 考虑使用com.google.common.base.Optional,您可以这样做:for (Entry<String, String> entries = cfg.getTypeMapping().entrySet()) {&nbsp; if (entry.getKey().startsWith(jsonType + "|")) {&nbsp; &nbsp; return Optional.of(entry);&nbsp; }}&nbsp;return Optional.absent();反而。当然,永远记住:Java 6 是。人们应该避免对其进行积极的开发,尤其是当必须依赖其他人来完成实际的反向移植工作时。

一只名叫tom的猫

流几乎总是可以转换为循环。您可以创建一个 for 循环,遍历条目集中的每个条目,检查它是否与您在filter. 如果是,立即中断循环Entry<String, String> result = null;for (Entry<String, String> entry : cfg.getTypeMapping().entrySet()) {&nbsp; &nbsp; if (entry.getKey().startsWith(jsonType + "|")) {&nbsp; &nbsp; &nbsp; &nbsp; result = entry;&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; }}请注意Optional,我使用 null 来表示“未找到”值,而不是 。
随时随地看视频慕课网APP

相关分类

Java
我要回答