代码之家  ›  专栏  ›  技术社区  ›  Ike Walker

基于Java中的一组关键字在关键字/值列表中放置占位符

  •  0
  • Ike Walker  · 技术社区  · 15 年前

    我有一组键和一个键/值对列表。这些值的形式是long,biginteger。

    // key/values pairs: Long,BigInteger
    List<Object[]> values;
    // id list that corresponds to the keys for the list above
    Set<Long> ids;
    

    如果键集的任何成员不作为键/值列表中的键存在,我希望将其添加到值为0的列表中。

    用Java做这件事的好方法是什么?

    3 回复  |  直到 15 年前
        1
  •  4
  •   justkt    15 年前

    各种各样的评论建议地图是一个很好的观点。换一个怎么样

    List<Object[]> values 
    

    你用

    Map<Long, BigInteger> values
    

    在这种情况下:

    for(Long id : ids) {
        if(!values.containsKey(id)) {
            values.put(id, BigInteger.ZERO);
        }
    }
    

    事实上,即使代码必须保持为书面形式,我也会考虑使用一个映射进行操作,方法是将列表预处理到一个映射中,然后将其转储回对象数组列表中。

        2
  •  3
  •   BalusC    15 年前

    用Java做这件事的好方法是什么?

    替换 Set<Long> List<Object[]> 由A Map<Long, BigInteger> .如果顺序不重要,则使用 HashMap . 如果要自动排序键,请使用 TreeMap . 如果要保持插入顺序,请使用 LinkedHashMap .

    例如。

    Map<Long, BigInteger> unorderedMap = new HashMap<Long, BigInteger>();
    Map<Long, BigInteger> orderedByKeys = new TreeMap<Long, BigInteger>();
    Map<Long, BigInteger> orderedByInsertion = new LinkedHashMap<Long, BigInteger>();
    

    这样你就可以使用 Map 处理键/值对的方法。例如。

    Long key = 1L;
    BigInteger value = map.get(key);
    if (value == null) {
        value = new BigInteger(0);
        map.put(key, value);
    }
    

    你甚至可以拿到所有的钥匙 Map#keySet() :

    Set<Long> keys = map.keySet();
    

    要了解有关地图的更多信息,请咨询 Sun's own tutorial 关于这个主题。

        3
  •  1
  •   Carl    15 年前

    我想你想用 Google Collections Multimap 实施。不要重新发明轮子。我怀疑ApacheCommons有类似的东西,但我更喜欢谷歌图书馆。

    查询没有值的键返回空集合。

    编辑:排序顺序、唯一性等选项都可用,只需根据您的需求选择正确的实现即可。