Reputation: 49
I am not able to convert the value which is the List<String>
, of the Map
into the String
.
Source code is as follows:
Map<String ,List<String>> profileFields)
String argValue[] = null;
int loopCounter = 0;
Object[] obj = profileFields.values().toArray();
for(int i = 0 ; i < obj.length ; i++){
System.out.println("Values####"+obj[i]);
argValue[loopCounter] = (String) obj[i];
}
This code is not working.
Please let me know, how I am able to convert these values to String.
Upvotes: 1
Views: 978
Reputation: 69002
You forgot to initialze argValue:
String argValue[] = new String[ profileFields.values().size() ];
and
loopCounter
isn't incremented either resue i or loopCounter++
This would work:
ArrayList<String> allLists = new ArrayList<String>();
for ( List<String> list : profileFields.values() ) {
allLists.addAll( list );
}
String[] argValue = new String[ allLists.size() ];
for ( int i = 0 ; i < argValue.length ; i++ ) {
argValue[i] = allLists.get( i );
System.out.println( "Values####" + argValue[i] );
}
EDIT:
You also replace the last loop (without printing) by
String[] stringArray = Arrays.copyOf(objectArray, objectArray.length, String[].class);
Upvotes: 0
Reputation: 15229
Map<String, List<String>> profileFields = new HashMap<String, List<String>>();
profileFields.put("s1", new ArrayList<String>() {
{
add("l11");
add("l12");
}
});
profileFields.put("s2", new ArrayList<String>() {
{
add("l21");
add("l22");
}
});
List<String> argValue[] = null;
int loopCounter = 0;
//this will get you an array of elements, each element representing a Map value
//your map Values are if type List<String>, so you'll get an array of Lists
Object[] obj = profileFields.values().toArray();
for(int i = 0 ; i < obj.length ; i++){
System.out.println("Values####"+obj[i]);
argValue[loopCounter] = (List<String>) obj[i];
}
Upvotes: 0
Reputation: 32969
Your array is an array of List<String>
.
Object[] obj = profileFields.values().toArray();
is actually
List<String>[] obj = profileFields.values().toArray();
because values
is returning a collection of List
objects.
Also Consider using Guava's ListMultimap which implements a Map
of Lists
.
Upvotes: 1
Reputation: 2776
You are missing the instantiation of the argValue-array.
Map<String ,List<String>> profileFields)
String argValue[] = null;
int loopCounter = 0;
Object[] obj = profileFields.values().toArray();
argValue = new String[obj.length];
for(int i = 0 ; i < obj.length ; i++){
System.out.println("Values####"+obj[i]);
argValue[loopCounter] = (String) obj[i];
}
Upvotes: 1