rms820
rms820

Reputation: 11

return dictionary using hashmap java

I am very new to java had a question regarding returning the dictionary with the help of hashmap. The problem is I have string array let say with four names and I have to iterate and differentiate name according to the string length and if the key does not match I have to create other list and if it matches I have to simply append the string.

Basically the expected output should be like this

3:kel
4:john,aron
5:sonny
6:abraham

I tried little bit but stuck code looks like this

public static void main(String arg[])
{   
    HashMap<integer, ArrayList<String>> map = new HashMap<integer,   ArrayList<String>>();

    ArrayList<String> namelist = new ArrayList<String>();
    obj.add("john");
    obj.add("kel");
    obj.add("abraham");
    obj.add("sonny");
    obj.add("aron");

    map.put(3, namelist);


    for (int i = 0; i < namelist.size(); i++) {

        String element = namelist[i];
        String nextElement = elements[i+1];
    }

}

Upvotes: 1

Views: 757

Answers (2)

Mureinik
Mureinik

Reputation: 311563

Java 8's streaming capabilities offer a pretty elegant one-liner for this with the built in groupingBy collector:

Map<Integer, List<String>> map =  
    obj.stream().collect(Collectors.groupingBy(String::length));

Upvotes: 0

hansod1
hansod1

Reputation: 324

Your datatypes on the HashMap are not ideal. You want HasMap<Integer, List<String>>, although you could use String as a key if you call toString on the integer length of the name before using it as a key. Then, loop through the obj list and check if the length of the string you're on (obj[i].length()) exists in map using map.containsKey(obj[i].length()). If it does exist, you will map.get(obj[i].length()).add(obj[i]), and if it doesn't you will create a new ArrayList containing obj[i] and use the .put method on the HashMap to add it.

In the code you posted, first appears to not be defined. I would rename obj to nameList, or something more descriptive. It's not an object.

Upvotes: 1

Related Questions