user2602860
user2602860

Reputation: 127

how to get the arraylist from the hashmap in java?

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.*;
//import java.util.Map.Entry;

public class teste{ 
    public static void main(String[] args){

    }
}

I just want the final arraylist for each key for display purpose which is :

The returning values of the key :[silicone baby dolls for sale, ego ce4, venus, sample,blue]

The returning values of the key :[apple, banana, key, kill]

Upvotes: 2

Views: 23891

Answers (3)

Isaac Sekamatte
Isaac Sekamatte

Reputation: 5598

ArrayList<String> values= new ArrayList<>(hashmap.values());

String could be any other object type

Upvotes: 2

user2663609
user2663609

Reputation: 427

HashMap hm=new HashMap();

ArrayList ln=new ArrayList();

  ln.add("hi");

  ln.add("heloo");

  ln.add(123);

 hm.put("somename", ln);

 ArrayList ls=(ArrayList)hm.get("somename");

Upvotes: 3

A4L
A4L

Reputation: 17595

No need for separate Lists for Keyword and Alternate.

What you need is Map which has as key the Keyword from your csv data and as value a List which holds all the Alternate values corresponding to a Keyword.

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

Note that putting a value into a map with a key which is already present in that map will overwrite the previous value. So you have to put the list only the first time you find a new Keyword, i.e. when trying to add an alternative for a keyword, first check whether the corresponding List exists in the map, if not then create a List and put into the map, then add the Alternate to that list.

while(...) {
    String keyword = ...;
    String alternate = ...;
    // check whether the list for keyword is present
    List<String> alternateList = alternateMap.get(keyword);
    if(alternateList == null) {
        alternateList = new ArrayList<>();
        alternateMap.put(keyword, alternateList);
    }
    alternateList.add(alternate);
}

// printing the result
for(Map.Entry<String, List<String>> alternateEntry : alternateMap.entrySet()) {
    System.out.println(alternateEntry.getKey() + ": " + 
           alternateEntry.getValue().toString());
}

EDIT

After running your code it seems to working fine. The List is returned by entry.getValue(). Just add this to the end of your main method:

for(Entry<String, ArrayList<String>> entry : example.items.entrySet()) {
    System.out.println(entry.getKey() + ": " +  entry.getValue().toString());
}

and it should give you the output you want

ego kit: [silicone baby dolls for sale, ego ce4, venus, sample, blue]
samsung: [apple, banana, key, kill]

Note: the code above was not compiled but should give you a hint how to map your data.

Upvotes: 5

Related Questions