Java 8 映射流

有没有办法让这段代码使用 Java 8?


public static boolean areBooleansValid(Map<String, Object> pairs, List<String> errors, String... values) {

    for (String value : values) {

        if (pairs.get(value) == null) {

            return false;

        } else if (!(pairs.get(value) instanceof Boolean)) {

            errors.add(value + " does not contain a valid boolean value");

            return false;

        }

    }

    return true;

}

一直在想这样的事情:


Stream<Object> e = Stream.of(values).map(pairs::get);

但是我怎样才能让它从这个流中返回不同的布尔值呢?


倚天杖
浏览 160回答 3
3回答

侃侃无极

如果您只想过滤掉pairs地图中存在的布尔值,则可以应用过滤功能:Stream.of(values).filter(value ->&nbsp; pairs.get(value) != null && pairs.get(value) instanceof Boolean)或者如果你想真正返回true和false值,你可以使用 map:return Stream.of(values).allMatch(value -> {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (pairs.get(value) == null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if ((pairs.get(value) instanceof Boolean)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; errors.add(value + " does not contain a valid boolean value");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; &nbsp; &nbsp; });

30秒到达战场

我认为你需要 Just :return&nbsp;Arrays.stream(values) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.allMatch(value&nbsp;->&nbsp;pairs.get(value)&nbsp;instanceof&nbsp;Boolean);笔记我error在你的方法中看不到任何原因也正如@Andy Turner在评论中提到的那样pairs.get(value) instanceof Boolean暗示pairs.get(value) != null你不需要使用pairs.get(value) != null

富国沪深

您可以使用以下方法重现与原始代码完全相同的行为public static boolean areBooleansValid(Map<String, Object> pairs,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;List<String> errors, String... values) {&nbsp; &nbsp; Optional<String> opt = Arrays.stream(values)&nbsp; &nbsp; &nbsp; &nbsp; .filter(s -> !(pairs.get(s) instanceof Boolean))&nbsp; &nbsp; &nbsp; &nbsp; .findFirst();&nbsp; &nbsp; opt .filter(s -> pairs.get(s) != null)&nbsp; &nbsp; &nbsp; &nbsp; .ifPresent(value -> errors.add(value+" does not contain a valid boolean value"));&nbsp; &nbsp; return !opt.isPresent();}就像您的原始代码一样,它只搜索第一个不是 a Boolean(可能是null)的项目,但仅当值不是 时才添加错误null。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java