3

I have a Dictionary in Python say

{ SERVER1 : [ (list1),(list2),....
  SERVER2 : [ (list2a),(list2b) ] }

Is it same can be implemented in Java ? I need to check each key if exist then I need to add the list to that key like appending the existing value without overriding Also need to read the key and value and traverse through each value of list

Kindly assist. Sorry to ask these question as it is my first program in Java

Raedwald
  • 46,613
  • 43
  • 151
  • 237
Marshall
  • 127
  • 3
  • 11

2 Answers2

4

In java, dictionaries are defined with the Map interface. The common implementations are TreeMap and HashMap:

Map<String,List<String>> servers = new HashMap<>();

servers.put("SERVER1", new ArrayList<String>());
servers.get("SERVER1").add("list1");
servers.get("SERVER1").add("list2");
...

Similarly, ArrayList and LinkedList are common implementations of the List interface.

Darth Android
  • 3,437
  • 18
  • 19
0

Because you want to save each value associated with a key, you need a HashMap that contains ArrayLists for values. This object should do what you need:

public class HashOfLists<K, V> {

    HashMap<K, ArrayList<V>> map = new HashMap<>();

    public ArrayList<V> get(K key) {
        return map.get(key);
    }

    public void put(K key, V value) {
        ArrayList<V> existingValues = get(key);
        if (existingValues == null) existingValues = new ArrayList<>();
        existingValues.add(value);
        map.put(key, existingValues);
    }

}

To use it you would do something a bit like this:

HashOfLists<String, String> servers = new HashOfLists<>();
servers.put("SERVER3", "PROCESS A");
servers.put("SERVER3", "PROCESS B");

//Getting a list containing "PROCESS A" and "PROCESS B"
ArrayList<String> processes = servers.get("SERVER3");
Brian Risk
  • 1,244
  • 13
  • 23
  • I am reading a file say Server1|cmd|blablal Server2|cmd|blablala Server1|cmd2|blablal Server2|cmd4|blabla Below code returning the last value of each server – Marshall Mar 18 '16 at 02:42
  • I am reading a file say Server1|cmd|blablal Server2|cmd|blablala Server1|cmd2|blablal Server2|cmd4|blabla Below code returning the last value of each server Server1|cmd2|blablal Server2|cmd4|blabla but I want some thing like {Server1 :[(cmd|blablal),(cmd2|blablal)],Server2:[(cmd|blablala),(cmd4|blabla)} – Marshall Mar 18 '16 at 02:51
  • code is Map map = new HashMap<>(); while((line=br.readLine())!=null) { String[] line_split = line.split("\\|"); if(line_split.length == 3) { map.put(line_split[0], (line_split[1] +"|"+ line_split[2])); } } System.out.println(map.keySet()); for (Map.Entry entry : map.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); System.out.println(key); System.out.println(value); } – Marshall Mar 18 '16 at 02:51