Jacob
Jacob

Reputation: 14741

Put Comma separated values in Collecton Object

I have a query String which receive as January, February, March

I would like to split the string by comma and would put the String in HashMap, so that when I retrieve I would like to get and do a null check the String as January, February, March

How can I do this?

Upvotes: 0

Views: 3112

Answers (3)

Pratik Singal
Pratik Singal

Reputation: 40

You can use the following code to store the months in a hash map.   

 import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Map;
    import java.util.Set;
    import java.lang.String;

    public class strings {
        public static void main(String [] args){
            String text = "jan,feb,march,april";
            String[] keyValue = text.split(",");
            Map<Integer, String> myMap = new HashMap<Integer, String>();
            for (int i=0;i<keyValue.length;i++) {
                myMap.put(i, keyValue[i]);
            }
             Set keys = myMap.keySet();
                Iterator itr = keys.iterator();

                Integer key;
                String value;
                while(itr.hasNext())
                {
                    key = (Integer)itr.next();
                    value = (String)myMap.get(key);
                    System.out.println(key + " - "+ value);
                }
        }
    }

The out put will be-
0 - jan
1 - feb
2 - march
3 - april


Further you can perform the check that you want

Upvotes: 1

CloudyMarble
CloudyMarble

Reputation: 37576

You can use the split function:

String[] monthsArray= yourString.split(",");

Then you can convert it to a HashSet like:

Set<String> months = new HashSet<String>(Arrays.asList(monthsArray));

Or to a list:

List<String> months = Arrays.asList(monthsArray)

Upvotes: 1

Sudhanshu Umalkar
Sudhanshu Umalkar

Reputation: 4202

Try something similar-

    final String input = "January, February, March, ...";
    final String[] months = input.split(",");
    final List<String> monthList = new ArrayList<String>();
    for(String month : months) {
        monthList.add(month);
    }

You can even convert from array to list directly, check Collections Framework API.

EDIT: monthList=Arrays.asList(months)

Upvotes: 1

Related Questions