【问题标题】:subtitude keys and values in TreeMap with other TreeMap in JavaTreeMap 中的 subtitude 键和值与 Java 中的其他 TreeMap
【发布时间】:2015-03-12 18:01:26
【问题描述】:

假设我有一个 TreeMap<String,List<String> first;TreeMap<String,String> Origin; 并且 first 中的每个键和每个值在原点都有一个等效键。如何用 Origin 的相关值替换 first 的键和值?例如

first {a = [b,c,d], e = [ f,g,h]}
origin {a=a1,b=b1,c=c1,d=d1,e = e1, g = g1, h=h1}

我需要得到这个 TreeMap DesiredMap {[a1 =b1,c1,d1],[e1 = f1,g1,h1]}

【问题讨论】:

  • 您实际上还没有问过问题。如果您的问题是:“我该怎么做?”我们会告诉您 (a) 请先尝试并发布您尝试过的内容,并且 (b) 您的问题写得太宽泛
  • 顺便说一句,这在使用 JSON 的 Javascript 中实现起来要容易得多

标签: java treemap


【解决方案1】:

您必须遍历 first TreeMap 上的条目。

for(Map.Entry<String, List<String>> entry : first.entrySet()) {

对于每个entry,获取oldKeyoldValues

String oldKey= entry.getKey();
List<String> oldValues= entry.getValue();

创建newKey

String newKey = origin.get(oldKey);           

然后遍历oldValues 中的每个值s 以从origin 中获取newValue 以创建newValues 的列表

List<String> newValues = new ArrayList<>();
for(String s : oldValues) {
    newValues.add(origin.get(s));
}

现在您有了newKeynewValues 将它们放入您的result TreeMap。

result.put(newKey, newValues);

转到下一个entry 并重复!

【讨论】:

    猜你喜欢
    • 2015-12-05
    • 1970-01-01
    • 1970-01-01
    • 2022-12-09
    • 2018-08-23
    • 1970-01-01
    • 2017-08-28
    • 1970-01-01
    • 2021-04-29
    相关资源
    最近更新 更多