I am using the following code:
{
// ...
String[] roles = new String[resultList.size()];
int i=0;
for (Iterator<Object[]> iter = resultList.iterator(); iter.hasNext();) {
roles[i] = new String();
Object[] objArr = iter.next();
roles[i] = objArr[0].toString();
i++;
}
return roles;
}
However, I get a ClassCastException saying cannot cast from java.lang.String to Object[].
try this:
{
// ...
String[] roles = new String[resultList.size()];
int i=0;
for (Iterator<String> iter = resultList.iterator(); iter.hasNext();) {
roles[i] = iter.next();
i++;
}
return roles;
}
Try this to convert an Object list to a String array:
// Create an object list and add some strings to it
List<Object> objectList = new ArrayList<>();
objectList.add("A");
objectList.add("B");
objectList.add("C");
// Create an String array with the same size of the object list
String[] stringArray = new String[objectList.size()];
// Iterate over the object list to fill the string array, invoking toString() in each object to get a textual representation from it
for (int i = 0; i < objectList.size(); i++) {
Object object = objectList.get(i);
stringArray[i] = object.toString();
}
// Iterate over the string array to print the strigs
for (String string : stringArray) {
System.out.println(string);
}
Can you make this:
Object[] objArr = iter.next();
Into this:
String[] objArr = (String[]) iter.next();
Related
I am creating an ArrayList of String Arrays in Java.. The code for the same is follows..
ArrayList<String[]> al = new ArrayList<String[]>();
for(int i = 0; i < t; i++) { // t is input by user representing size of arraylist
int k = sc.nextInt();
String[] s = new String[k]; // k string values input by user
}
Iterating to print the values of ArrayList
Iterator it = al.iterator();
while(it.hasNext()){
for(int i = 0; i < (it.next(new String[])).length; i++) { // error for dimension missing
System.out.println((it.next(new String[])).length); // error for dimension missing
}
}
I get an error of "array dimension missing" in the indicated lines. Please suggest how to convert ArrayList Object as String Array.
Try this
Iterator<String[]> it = al.iterator();
while(it.hasNext()){
String temp [] = it.next();
for(int i = 0; i < temp.length; i++) {
System.out.println(temp.length);
}
}
your new String[]
requires size, because you're making new array i.e
String[] myStringArray = new String[5];
also, your iteration to print values make no sense, try :
for(String[] stringArray: al) {
System.out.println("Size: " + stringArray.length);
for(String s: stringArray) {
System.out.println(s);
}
}
I'm trying to Convert List of Object into List of Strings
My List of Custom Object is like this
convertedData
{ rawMaterialId: "3411", batchNumber: "166,465,963,962,785",
location: "hhh,ooo,hhh,uio,pop", quantity: "900,302,560,650,989" }
I'm trying to convert this JSON object into List of Strings
It should look like this,
List[
"3411" ,"166" ,"465" ,"963" ,"hhh","ooo","pop","900","302","560"]
I tried with below code
String[] array = new String[convertedData.size()];
int index = 0;
for (Object value : convertedData) {
array[index] = (String) value;
index++;
}
Any suggestions and correction welcomed.Thanks in advance.
You should split the converted data.
List<String> list = new ArrayList<>();
for (Object value : convertedData) {
if (value instanceof String) {
String str = (String) value;
list.addAll(Arrays.asList(str.split(",")));
}
}
String[] array = list.toArray(new String[list.size()]);
List<String> list = new ArrayList<>();
for (Object value : convertedData) {
String[] wordList = ((String) value).split(",");
for (String val : wordList) {
list.add(val);
}
}
String[] stringArray = list.toArray(new String[list.size()]);
Wil this work, how can i compare a string array elements to a predefined string and copy to a new array.
String element={"France","Germany","USA","France","Italy"}
String finalelement[]= null;
String compareelement = "France";
int l =elements.length;
int i1 = 0;
for(int i=0; i<l; i++)
{
//comparing the elements
if((compareelement.equals(element[i])))
{
//assigning the array element
finalelement[i1]=element[i];
i1++;
}
}
It's better to do it this way:
List<String> elements = new ArrayList<>();
elements.add("France");
elements.add("Germany");
elements.add("USA");
elements.add("France");
elements.add("Italy");
List<String> finalElement = new ArrayList<>();
String compareElement = "France";
for (String str : elements) {
if (compareElement.equals(str)) {
finalElement.add(str);
}
}
At least the first line is wrong:
String element={"France","Germany","USA","France","Italy"}
String[] elements = new String[]{"France","Germany","USA","France","Italy"}
I am trying to read a file which has say
Name,Date,Place
Tom,1/1/2010,America
Dick,2/2/2011,China
Harry,3/3/2012,Germany
And adds the column headers to a String and the values to an ArrayList.
HashMap<String columnName ,ArrayList<String> Value>
So the program should run like,
if(lineNumber == 1)
{
interate through values and create headers
}
else
add values to corresponding header list
My problem is I do not know how I can reference the arraylist in the else part of the code.
If anybody has done something similar I would like to hear from you !
Edit
So I have something like this so far,
public void consumeLine(String path,int lineNumber,List line){
if(lineNumber == 1)
{
ListIterator listIterator = line.listIterator();
while(listIterator.hasNext())
{
hashMap.put(listIterator.next().toString(),new ArrayList<String>());
}
}
You want to create an ordered list of the column names, and iterate through that as you iterate through the values in each row.
Something like this (untested code!):
ListIterator listIterator = line.listIterator();
if(lineNumber == 1)
{
while(listIterator.hasNext())
{
String key = listIterator.next().toString();
keyList.add(key); // keyList is a List<String> instance field.
hashMap.put(key, new ArrayList<String>());
}
} else {
Iterator<String> keyIterator = keyList.iterator();
while(keyList.hasNext() && listIterator.hasNext())
{
String key = keyList.next();
String value = listIterator.next();
ArrayList<String> values = hashMap.get(key);
values.add(value);
}
}
Try it:
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
int lineNumber = 1;
String[] columnName = null;
ArrayList<String[]> value = new ArrayList<String[]>(); // temp array
String line;
String[] arr;
while (reader.ready())
if (!(line = reader.readLine()).isEmpty()) {
arr = line.split("\\s+");
if (lineNumber == 1)
columnName = arr;// create headers
else
value.add(arr);// create values
lineNumber++;
}
// transform data
for (int i = 0; i < columnName.length; i++) {
ArrayList<String> ar = new ArrayList<String>();
for (int j = 0; j < value.size(); j++)
ar.add(value.get(j)[i]);
map.put(columnName[i], ar);
}
System.out.println(map);
}
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.
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];
}
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.
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];
}
You forgot to initialze argValue:
String argValue[] = new String[ profileFields.values().size() ];
and
loopCounterisn'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);