将HashMap的特定键值集复制到另一个

时间:2019-10-15 17:53:22

标签: java hashmap

我正在尝试获取HashMap的特定键的值,然后将其复制到新的键中。有没有比我尝试的方法更有效的方法?预先感谢!

LinkedHashMap<String, List<String>> TradeDetailsNewOrPrevious = new LinkedHashMap<String, List<String>>();

LinkedHashMap<String, List<String>> temp = new LinkedHashMap<String, List<String>>();

temp = (LinkedHashMap<String, java.util.List<String>>) TradeDetailsModified.get(tradeID);

TradeDetailsNewOrPrevious = (LinkedHashMap<String, java.util.List<String>>) temp.clone();

我收到“ ClassCastException:

  

java.util.ArrayList无法转换为java.util.LinkedHashMap“

"temp = (LinkedHashMap<String, java.util.List<String>>) TradeDetailsModified.get(tradeID);行中的

1 个答案:

答案 0 :(得分:0)

您的代码没有反映您的问题,我理解的是-您需要特定键或一组键的值,然后要将这些值复制到一个新值中,这是我尝试过的,您可以循环更新此内容:

      LinkedHashMap<String, List<String>> tradeDetailsNewOrPrevious = new LinkedHashMap<>();

  //    taking some values for a clear understanding
  tradeDetailsNewOrPrevious.put("AA", Arrays.asList("a", "aa", "aaa"));
  tradeDetailsNewOrPrevious.put("BB", Arrays.asList("b", "bb", "bbb"));
  tradeDetailsNewOrPrevious.put("CC", Arrays.asList("c", "cc", "ccc"));

  LinkedHashMap<String, List<String>> temp = new LinkedHashMap<String, List<String>>();

  List<String> tradeIDs = Arrays.asList("AA", "CC", "DD");

  for (String tradeID : tradeIDs)
  {
     if (tradeDetailsNewOrPrevious.keySet().contains(tradeID))
     {
        temp.put(tradeID, tradeDetailsNewOrPrevious.get(tradeID));
     }
  }

它将复制所有具有与tradeID匹配的键的值。

如果这不是您想要的内容,请在评论中明确说明问题。