【问题标题】:How to convert hash map keys into list?如何将哈希映射键转换为列表?
【发布时间】:2015-10-27 11:50:58
【问题描述】:

我有一个哈希映射,我正在尝试将键转换为列表。代码如下:

List<ARecord> recs = new ArrayList<ARecord>();

HashMap<String, ARecord> uniqueRecs = new HashMap<String, ARecord>();
for(ARecord records:recs){
    if(!uniqueRecs.containsKey(records.getId())){
        uniqueRecs.put(records.getId(), records);
    }
}

当我尝试做时

List<ARecord> finalRecs = new ArrayList<ARecord>(uniqueRecs.keySet());

错误:

构造函数 ArrayList(Set) 未定义”。

如何将 Hashmap 键转换为 List&lt;ARecord&gt;finalRecs?

【问题讨论】:

    标签: java arraylist hashmap


    【解决方案1】:

    您的uniqueRecs 具有String 类型的密钥。你必须这样做:

    List<String> keys = new ArrayList<>(uniqueRecs.keySet());
    

    List<ARecord> values = new ArrayList<>(uniqueRecs.values());
    

    【讨论】:

    • 有没有办法将 List 键转换为 List
    • 地图中的 ARecords 不是键,它们是值!您必须决定最终要获得哪些实体的列表:ARecords 或 Strings。如果 ARecords - 然后取 Map 的值,如果 Strings - 取 keySet。
    • 我想要keySet。一旦我得到它,我就会传递给另一个方法,该方法采用 List。我不知道如何将哈希映射的键作为 List 传递
    • @Jay:这种说法毫无意义。密钥是Strings。 “如何将哈希映射的键作为 List 传递”没有意义,因为 键不是 ARecords。 那是 值。跨度>
    • @Jay,如果uniqueRecs中的记录确实是唯一的,顾名思义,意味着地图中所有ARecords都有唯一的id,那么你可以简单地使用new ArrayList&lt;&gt;(uniqueRecs.values()) as ka4eli在这里建议。
    【解决方案2】:

    我想修改现有列表对我有用的是:

    list.addAll(map.keySet());
    

    【讨论】:

      【解决方案3】:

      我认为“现在”最好的方法是:

      List<Integer> result = map.keySet().stream().collect(Collectors.toList());
      

      这将不会抛出任何警告,并将正确获取List&lt;Integer&gt; 泛型。

      【讨论】:

        【解决方案4】:

        以下在 Java 1.7 和 1.8 下工作:

        List<ARecord> finalRecs = new ArrayList<ARecord>();
        for (final String key : uniqueRecs.keySet()) {
          finalRec.add(new ARecord() {
            public String gettld() {
               return key;
            }
          });
        }
        

        【讨论】:

        • 我收到错误“List 类型中的方法 addAll(Collection extends ARecord>) 不适用于参数 (Set)”
        • @Jay 修改了答案,用地图的值而不是键填充列表。
        • 我真的想要钥匙。有没有办法获取密钥并转换为 List
        • 这是一个接口:public interface ARecord {public String gettId()}
        猜你喜欢
        • 1970-01-01
        • 2011-12-10
        • 2011-10-25
        • 1970-01-01
        • 1970-01-01
        • 2012-12-05
        • 2011-09-30
        • 2011-09-29
        • 2011-01-16
        相关资源
        最近更新 更多