veleda
veleda

Reputation: 147

How to split a string into a map with a list of values?

I am a bit stuck with my application, and I am not quite sure what to search for. So I am hoping someone here may help me out.

I have a list of Strings, that looks like this:

Cake;carrot
Cake;apple
Cake;spicy
Pizza;pepperoni
Pizza;mozzarella

... and so on. I want to put this data into a Map<String, List<String>>, where Cake and Pizza will make up the keys in my Map. Having [carrot, apple, spicy] as Cake's values, and [pepperoni, mozzarella] as Pizza's values.

How may I achieve this? Thanks in advance for any help.

Upvotes: 0

Views: 3289

Answers (3)

Abhishek
Abhishek

Reputation: 2525

public static void main(String[] args) {
    List<String> data = new ArrayList<String>();
    Map<String, List<String>> finalData = new HashMap<String,List<String>>();
    data.add("Cake;carrot");
    data.add("Cake;apple");
    data.add("Cake;spicy");
    data.add("Pizza;pepperoni");
    data.add("Pizza;mozzarella");
    for (String dataString : data) {
        List<String> temp = null;
        if (finalData.get(dataString.split(";")[0]) == null) {
            temp = new ArrayList<String>();
            temp.add(dataString.split(";")[1]);
            finalData.put(dataString.split(";")[0], temp);
        } else {
            temp = finalData.get(dataString.split(";")[0]);
            temp.add(dataString.split(";")[1]);
            finalData.put(dataString.split(";")[0], temp);
        }
    }
    System.out.println(new Gson().toJson(finalData));
}

Complete working solution.

Upvotes: 0

sameera sy
sameera sy

Reputation: 1718

You can try this, use a hashmap, store consecutive strings with (space) as the delimiter, finally split the string when you want it as a list

//Assuming your list to be the variable 'list'
HashMap<String,String> hm = new HashMap<>();
for(val : list){
    String st[] = val.split(";");
    if(hm.get(st[0])==null){
        hm.put(st[0],st[1]);
    }
    else{
        hm.put(st[0],hm.get(st[0])+" "+st[1]);
    }
}

when You want the string array of say pizza back then

String pizz[] = (hm.get("pizza")).split(" ");

pizz[] will have your array, cheers!

Upvotes: 0

Nadir
Nadir

Reputation: 1819

Just iterate over your list using String.split()

ArrayList<String> myList;
HashMap<String, List<String>> myMap = new HashMap<>();
for(String s : myList)
{
   String[] split = s.split(";");
   List<String> bucket = myMap.get(split[0]);
   if(bucket == null) 
   {
       bucket = new ArrayList<String>();
       myMap.put(split[0], bucket);
   }

   bucket.add(split[1]);
}

Upvotes: 3

Related Questions