How to convert List of Object into List of Strings - java

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()]);

Related

Convert Arrays inside ArrayDeque to String

I am trying to return a string pulled from the 2nd element of a given array inside of an ArrayDeque
I tried casting it and toString and concatenation after ToArray but I get this... I need to return it as a String
"The type of the expression must be an array type but it resolved to String"
ArrayDeque<String[]> bindings_and_var = new ArrayDeque();
public ArrayDeque<String[]> pushBindings(String var, String bindings) {
//var first element, bindings 2nd
String[] this_bindings_and_var = new String[2];
bindings_and_var.addLast(this_bindings_and_var);
return bindings_and_var;
}
public ArrayDeque<String[]> bindingsVal() {
return bindings_and_var;
}
public String lookup(int index) {
String[] array = (String[]) bindings_and_var.toArray();
//PROBLEM AREA vvv
String s = "" + array[index][1];
return s;
Your lookup method should look like this:
public String lookup(int index)
{
int counter = 0;
for (Iterator<String[]> itr = bindings_and_var.iterator(); itr.hasNext();)
{
String[] t = itr.next();
if (counter == index)
{
return t[1];
}
counter++;
}
}
You have defined your Deque as String[] while when you are doing bindings_and_var.toArray(); you would receive object array with each object as String array. Try,
Object[] array = (String[]) bindings_and_var.toArray();
Object obj = array[index];
String[] myArray = (String[])obj;
String s = "" + myArray[1];
Or
int i = 0;
for (String[] s : bindings_and_var) {
if (i == index) {
return s[1];
}
i++;
}
so that you don't have to iterate the whole collection.

Concatenating elements of ArrayList while iterating

I am interested in concatenating a string to elements of an arraylist while iterating.When I run the below code,I am getting a ConcurrentModificationException.My code is:
ArrayList<String> list=new ArrayList<String>();
list.add("000);
list.add("00");
list.add("0");
for(String s:list)
{
if(s.length()==1)
{
String s2="000" + s;
list.add(s2);
}
if(s.length()==2)
{
String s2="00" + s;
}
if(s.length()==3)
{
String s2="0" + s;
}
}
My question is how to add the concatenated strings back to list without using StringBuilder as when I use a StringBuilder,it is causing other parts of my program to malfunction? So just need some guidance.
I would just use List.set:
List<String> list = new ArrayList<String>();
list.add("000");
list.add("00");
list.add("0");
for (int i = 0; i < list.size(); i++) {
String value = list.get(i);
list.set(i, ("0000" + value).substring(value.length()));
}
The exception will occur if you change the contents of the list (i.e. add or remove an element) anywhere in your for loop.
ArrayList<String> list=new ArrayList<String>();
list.add("000);
list.add("00");
list.add("0");
ArrayList<String> itemsToAdd = new ArrayList<String>(); // <======
for(String s:list) {
if(s.length()==1) {
String s2="000" + s;
//list.add(s2); DONT DO THIS
itemsToAdd.add(s2); // DO THIS INSTEAD
}
if(s.length()==2) {
String s2="00" + s;
}
if(s.length()==3) {
String s2="0" + s;
}
}
// NOW APPEND THE LIST
// This is safe as the iteration is complete.
list.addAll(itemsToAdd.add);
make a second list
add the new elements to that second list
add all the elements in the second list back into the first one after you're done iterating
Have a look at this one: Modifying Java ArrayList while iterating over it
Short story: Java won't let you change a list that you're iterating over. Instead, make a copy by putting the list to be cloned into the new arraylist's constructor arguments and then change the new list:
ArrayList<String> list=new ArrayList<String>();
list.add("000);
list.add("00");
list.add("0");
ArrayList<String> listSecond =new ArrayList<String>(list);
for(String s:list)
{
if(s.length()==1)
{
String s2="000" + s;
listSecond.add(s2);
}...
Your list.add(s2) is a problem. You just can't play with lists while iterating (well with an iterator you can delete items). Here's a possible solution:
ArrayList<String> list=new ArrayList<String>();
list.add("000");
list.add("00");
list.add("0");
List<String> newOnes = new ArrayList<>();
for(String s:list)
{
if(s.length()==1)
{
String s2="000" + s;
newOnes.add(s2);
}
if(s.length()==2)
{
String s2="00" + s;
}
if(s.length()==3)
{
String s2="0" + s;
}
}
list.addAll(newOnes);
create a tempList and add the element to tempList and at last assign tempList to list
public static void main (String[] args) throws Exception
{
ArrayList<String> list=new ArrayList<String>();
ArrayList<String> tempList=new ArrayList<String>();
list.add("000");
list.add("00");
list.add("0");
for(String s:list)
{
if(s.length()==1)
{
String s2="000" + s;
tempList.add(s2);
}
if(s.length()==2)
{
String s2="00" + s;
tempList.add(s2);
}
if(s.length()==3)
{
String s2="0" + s;
tempList.add(s2);
}
}
list=tempList;
System.out.println(list);
}
Modifying your list while iterating: (more generic and short)
ArrayList<String> list= new ArrayList<>();
String zeros = "00000000";
list.add("000");
list.add("00");
list.add("0");
for(int i=0;i<list.size();i++) {
String s = list.get(i) + zeros.substring(0,4-list.get(i).length());
list.set(i,s);
}
for (String s : list)
System.out.println(s);

ClassCastException String to Object[]

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();

Java - Type mismatch: cannot convert from element type Object to String

I'm having this error:
Type mismatch: cannot convert from element type Object to String
This is the code in error:
public List<String> customPrefixes(PermissionUser u)
{
List returnlist = new ArrayList();
for (String k : u.getAllPermissions().keySet()) {
List perms = (List)u.getAllPermissions().get(k);
for (String s : perms) {
String[] split = s.split(".");
if ((split.length >= 3) &&
(split[0].equalsIgnoreCase("plugin")) &&
(split[1].equalsIgnoreCase("prefix"))) {
returnlist.add(split[2]);
}
}
}
return returnlist;
}
try this :
public List<String> customPrefixes(PermissionUser u)
{
List<String> returnlist = new ArrayList<String>();
for (String k : u.getAllPermissions().keySet()) {
List<String> perms = (List<String>)(u.getAllPermissions()).get(k);
for (String s : perms) {
String[] split = s.split(".");
if ((split.length >= 3) &&
(split[0].equalsIgnoreCase("plugin")) &&
(split[1].equalsIgnoreCase("prefix"))) {
returnlist.add(split[2]);
}
}
}
return returnlist;
}
You were missing "<String>" in the List declaration
I think you're casting is wrong..
What is u.getAllPermissions().get(k); should return? List of something?
if it does so you need to add type of the generic list
List<String> perms = (List<String>)u.getAllPermissions().get(k);
If that doesn't work you can also try to do
for (Object o : perms) {
String s = o.toString();
.....
}
Hope that helps.. If not answer my question and it will be easier to help
Another reason for this error can be the way you have initialized your container; as a case in point;
you have initialize list2 as below:
List list2 = new ArrayList <Integer>();
instead of
List<Integer> list2 = new ArrayList <Integer>();
So, you are looping over a wrong type of container ( if we can call this a container) as below :
for(Integer x:list2){
System.out.println(x);
}
Thus, you need to revise the way you have initialize your container ( here is a list) and there is no problem with your datatype, etc.

Java Mixing variable String[] with String in one only array of strings

Suppose this:
String s0 = "01234";
String[] S1 = {"jkl","abc","xyz"};
String[] S2 = {"OPQ","ghi","STU"};
String s3 = "56789";
get_AllStrings(s3, S1, S2, s0);
The returned String[] must be:
String[] NewArray = {"56789","OPQ","ghi","STU","01234"}
I want to obtain this strings like only one array of strings...
Here my method:
public String[] get_AllStrings(String... argString) { //Only String or String[]
int TheSize = 0;
for (int i = 0; i<argString.length; i++) {
if(argString[i]!= null && argString[i].getClass().isArray()) {
String[] OneArray = (String [])argString[i];
TheSize += OneArray.length;
} else {
TheSize += 1;
}
}
String[] NewArray = new String[TheSize];
int ThePos = 0;
for (int i = 0; i<argString.length; i++) {
if(argString[i]!= null && argString[i].getClass().isArray()) {
String[] OneArray = argString[i];
System.arraycopy(OneArray, 0, NewArray, ThePos, OneArray.length);
ThePos += OneArray.length;
} else {
String[] OneArray = {argString[i]};
System.arraycopy(OneArray, 0, NewArray, ThePos, 1);
ThePos += OneArray.length;
}
}
return NewArray;
}
But, is not working...
What you want to do is to use an ArrayList instead of an array.
public static String[] getAllStrings(Object ... argString) {
ArrayList<String> list = new ArrayList<String>();
for (Object stringOrArray : argString) {
if (stringOrArray instanceof String)
list.add((String) stringOrArray);
else {
String[] strings = (String) stringOrArray;
list.addAll(Arrays.asList(strings));
}
}
return list.toArray(new String[list.size()]);
}
I changed your code a bit and got this:
public static String[] get_AllStrings(Object... argString) {
ArrayList<String> strings = new ArrayList<String>();
for (int i = 0; i<argString.length; i++) {
if(argString[i]!= null && argString[i].getClass().isArray()) {
String[] OneArray = (String [])argString[i];
for(String str : OneArray)
strings.add(str);
} else {
strings.add((String)argString[i]);
}
}
return (String[])strings.toArray();
}
I could not get it to accept both String and String[] with your method signature, but a change to Object... did the trick. You can use an ArrayList to create the array directly instead of looping through everything twice.
unfortunately, you're running up against Java's type system here.
String and String[] are not subtypes.
so a variable, or array can only hold one or the other.
Using object, as done by #Johan Henriksson throws away any type safety assurances from the compiler, since any object can be put in the array. this is okay if you have some garuantee that you'll only ever have Strings, and you'll need to cast to string on pulling out of the collection.
I'm not sure exactly what you're trying to achieve here
So I'm not sure how to go about resolving this.
if you just want all the strings from all sources in a collection of some sort, I'd use a list
it's unclear where you're getting these strings and string arrays from however.
You can't pass a String[] into an element of a varargs String... parameter.
The only way to accept either String or String[] is a "typeless" varargs Object..., because Object is the only common type to both.
public static String[] get_AllStrings(Object... args) {
ArrayList<String> result = new ArrayList<String>();
for (Object o : args) {
if (o instanceof String) {
result.add((String)o);
} else if (o instanceof String[]) {
result.addAll(Arrays.asList((String[])o));
} else {
throw new IllegalArgumentException();
}
}
return (String[])result.toArray();
}

Categories

Resources