如何将python dict对象转换为java等效对象?

如何将python dict对象转换为java等效对象?,java,python,hashmap,dictionary,Java,Python,Hashmap,Dictionary,我需要将python代码转换为等效的java代码。Python通过提供许多快捷功能,使开发人员的生活变得非常简单。但现在我需要将其迁移到Java。我想知道java中dict对象的等价物是什么?我试过使用HashMap,但生活就是地狱。首先考虑这个问题, # Nodes is a dictionary -> Key : (Name, Strength) for node, (name, strength) in nodes.items(): nodes[node] = (name,

我需要将python代码转换为等效的java代码。Python通过提供许多快捷功能,使开发人员的生活变得非常简单。但现在我需要将其迁移到Java。我想知道java中dict对象的等价物是什么?我试过使用HashMap,但生活就是地狱。首先考虑这个问题,

#  Nodes is a dictionary -> Key : (Name, Strength)
for node, (name, strength) in nodes.items():
    nodes[node] = (name, new_strength)
那么如何将其转换为Java呢? 首先,我使用HashMap对象

Map<Integer, List> nodesMap = new HashMap<Integer,List>();
/* For iterating over the map */
Iterator updateNodeStrengthIterator = nodesMap.entrySet().iterator(); 
while(updateNodeStrengthIterator.hasNext()){ }    
Map nodesMap=newhashmap();
/*用于在地图上迭代*/
迭代器updateNodeDestrengthiterator=NodeMap.entrySet().Iterator();
while(updateNodeDestrengthiterator.hasNext()){}

我的问题是获取包含名称和强度的列表部分,然后更新强度部分。有没有可行的办法?我应该考虑一些不同的数据结构吗?请帮助。

Java没有内置元组的等价物。您必须创建一个类,将这两个类封装在一起以模拟它。

好的,总是有。 这里有一点,它提供了一个很好的python/java并行视图

Jython类似于Java的 收集类要多得多 与核心紧密结合 语言,允许更简洁 描述和有用的功能。 例如,请注意差异 在Java代码之间:

map = new HashMap();
map.put("one",new Integer(1));
map.put("two",new Integer(2));
map.put("three",new Integer(3));

System.out.println(map.get("one"));

list = new LinkedList();
list.add(new Integer(1));
list.add(new Integer(2));
list.add(new Integer(3));
还有Jython代码:

map = {"one":1,"two":2,"three":3}
print map ["one"]
list = [1, 2, 3]

编辑:仅使用put()替换值有什么问题

map.put(key,new_value);
下面是一个小示例程序:

static public void main(String[] args){
    HashMap<String,Integer> map = new HashMap<String,Integer>();
     //name, age
    map.put("billy", 21);
    map.put("bobby", 19);
    year(map);
    for(String i: map.keySet()){
        System.out.println(i+ " " + map.get(i).toString());
    }
}
// a year has passed
static void year(HashMap<String,Integer> m){
    for(String k: m.keySet()){
        m.put(k, m.get(k)+1);
    }
}
static public void main(字符串[]args){
HashMap=newHashMap();
//姓名、年龄
地图放置(“比利”,21岁);
地图.put(“bobby”,19岁);
年份(地图);
for(字符串i:map.keySet()){
System.out.println(i+“”+map.get(i.toString());
}
}
//一年过去了
静态无效年(HashMap m){
对于(字符串k:m.keySet()){
m、 put(k,m.get(k)+1);
}
}

为(名称、强度)元组创建一个类可能是最简单的方法:

如果合适,添加getter、setter和构造函数

然后可以在地图中使用新类:

Map<Integer, NameStrength> nodesMap = new HashMap<Integer, NameStrength>();
或者像这样:

for (NameStrength nameStrength : nodesMap.values()) {}
for (Entry<Integer, NameStrength> entry : nodesMap.entrySet()) {}
for(条目:nodesMap.entrySet()){

谢谢你的提示。但是由于一些限制,我不能使用Jython。谢谢。这很有帮助。我只是希望得到更简洁的方法。啊,不幸的是,简洁不是Java的优势之一。。。
for (Entry<Integer, NameStrength> entry : nodesMap.entrySet()) {}