I need to convert a python code into an equivalent java code. Python makes life very easy for the developers by providing lots of shortcut functionalities. But now I need to migrate the same to Java. I was wondering what will the equivalent of dict objects in java? I have tried using HashMap but life is hell. For starters consider this,
# Nodes is a dictionary -> Key : (Name, Strength)
for node, (name, strength) in nodes.items():
nodes[node] = (name, new_strength)
So how to go about converting this into Java? For starters I used HashMap object so,
Map<Integer, List> nodesMap = new HashMap<Integer,List>();
/* For iterating over the map */
Iterator updateNodeStrengthIterator = nodesMap.entrySet().iterator();
while(updateNodeStrengthIterator.hasNext()){ }
My problem is in getting the List part which contains Name & Strength & then updating the Strength part. Is there any feasible way to do this? Should I consider some different data structure? Please help.
It's probably easiest to just create a class for the (Name, Strength) tuple:
class NameStrength {
public String name;
public String strength;
}
Add getters, setters and a constructor if appropriate.
Then you can use the new class in your map:
Map<Integer, NameStrength> nodesMap = new HashMap<Integer, NameStrength>();
In Java 5 and up, you can iterate like this:
for (NameStrength nameStrength : nodesMap.values()) {}
or like this:
for (Entry<Integer, NameStrength> entry : nodesMap.entrySet()) {}
well there's always jython. here's a little bit from this article that offers a good side by side view of python/java
The Jython analogues to Java's collection classes are much more tightly integrated into the core language, allowing for more concise descriptions and useful functionality. For example, notice the difference between the Java code:
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));
and the Jython code:
map = {"one":1,"two":2,"three":3} print map ["one"] list = [1, 2, 3]
map.put(key,new_value);
here's a small example program:
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With