【问题标题】:Can I take a part of a map and test the key I use?我可以获取地图的一部分并测试我使用的密钥吗?
【发布时间】:2019-12-28 17:59:16
【问题描述】:

我想使用方法参数中的键从另一个 TreeMap 创建一个过滤后的 TreeMap,但我还想测试这些值?

我试过这个:

    public TreeMap<Integer, List<String>> getInfoById(int... ids) {
        try (IntStream stream = Arrays.stream(ids)) {
            return stream.boxed().collect(
                    Collectors.toMap(
                            i -> i,
                            info::get, //Info is a TreeMap<Integer, List<String>>
                            (i1, i2) -> {
                                throw new IllegalStateException("Two keys are similar");
                            },
                            TreeMap::new
                    )
            );
        }
    }

但我想确保在ids 中不会有超过 807 的数字(因为总是有 807 密钥,所以我不希望有人寻找 808 密钥)

如果我的流不包含超过 807 的 int,我可以添加什么来查看

编辑:更准确地说,如果其中一个 id 超过 807,我想抛出异常

【问题讨论】:

  • 你的意思是,你只需要ids Map ?
  • stream.filter(i -&gt; i &lt; 808).boxed()...?
  • 如果 id 为 > 807 是否可以抛出异常
  • if (Instream.of(ids).anyMatch(id -&gt; id &gt; 807)) { throw new IllegalArgumentException("..."); } docs.oracle.com/javase/8/docs/api/java/util/stream/…

标签: java dictionary lambda filter java-stream


【解决方案1】:

评论中给出的答案,但是: 如果我只想过滤而不回退,我应该使用

stream.filter(i -> i < 808).boxed()...

但如果发生这种情况我想抛出一个错误,所以我使用了

if (Instream.of(ids).anyMatch(id -> id > 807)) { throw new IllegalArgumentException("..."); }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-08
    • 2012-01-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多