Convert String results[] To ArrayList<String> alist; [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How can I convert String[] to ArrayList<String>
hi please can anyone help me I have :
private String results[];
private ArrayList<String> alist;
I want convert
String results[] to ArrayList<String>

Convert String Array to ArrayList as
String[] results = new String[] {"Java", "Android", "Hello"};
ArrayList<String> strlist =
new ArrayList<String>(Arrays.asList(results));

You can use the Arrays.asList() method to convert an array to a list.
E.g. List<String> alist = Arrays.asList(results);
Please note that Arrays.asList() returns a List instance, not an ArrayList instance. If you really need an ArrayList instance you can use to the ArrayList constuctor an pass the List instance to it.

Try this:
ArrayList<String> aList = new ArrayList<String>();
for(String s : results){
aList.add(s);
}
What this does is, it constructs an ArrayList of Strings called aList: ArrayList<String> aList = new ArrayList<String>();
And then, for every String in results: String s : results
It add's that string: aList.add(s);.
Hope this helps!

You should use
Arrays.asList(results)
by default, unless you absolutely for some reason must have an ArrayList.
For example, if you want to modify the list, in which case you use
new ArrayList(Arrays.asList(results))

Related

How to transform String[] into collection? [duplicate]

This question already has answers here:
Converting array to list in Java
(24 answers)
How to convert an Array to a Set in Java
(19 answers)
Closed 3 years ago.
I am trying to get a String Collection in my Java code, so i'm trying something like this:
Collection c = new String[]{};
But i get this error: incompatible types: String[] cannot be converted to Collection.
Is there a way to convert String[] into Collection without doing something like this:
var array = new String[]{"Apple", "Banana"};
var arrayList = new ArrayList<String>();
for (String fruit : array) {
arrayList.add(fruit);
}
Collection c = arrayList;
Depends on the Collection. For example, if you want a List, use Arrays::asList
List<String> list = Arrays.asList(array);
or as a Collection:
Collection<String> list = Arrays.asList(array);
Be aware that this does not return a new List. It returns a fixed size view of the array you pass to the method, meaning that if the array changes, so does the list and vice versa. You cannot, however, change the length of the list.
There is no method for transforming an Array into a Set, but you can, for example, use a stream to achieve this:
Set<String> set = Arrays.stream(array).collect(Collectors.toSet());
Arrays are not Collections.
You will need to convert.
https://docs.oracle.com/javase/10/docs/api/java/util/Arrays.html
Arrays.asList(yourStringArray)
Java 8+
String[] arr = { "A", "B", "C", "D" };
List<String> list = Arrays.stream(arr).collect(Collectors.toList());

How to name a variable dynamically? - Java [duplicate]

This question already has answers here:
How do I declare and initialize an array in Java?
(31 answers)
Closed 9 years ago.
I want to know how I can name a variable dynamically.
If there are 3 items in a list then it should create 3 different object for each item.
Like:
ArrayList<String> list1;
ArrayList<String> list2;
ArrayList<String> list3;
So it should count up or anything like that.
if there are 4 items in a list it should create 4 variables.
How can I achieve that?
Edit:
I tried this but it says me an error that I can't create a generic array of Info.
ArrayList<Info> listForLg[] = new ArrayList<Info>[];
for (int i = 0; i < sizeOfKfzList; i++) {
listForLg[i] = new ArrayList<Info>();
listForLg[i].add(logInfo);
}
Can you help me?
Use arrays
ArrayList<String> list[] = new ArrayList<String>[3]; //or 4 or n
Then access them like
list[0] = "123";
Use Array for this...
ArrayList<String> yourlist[] = new ArrayList<String>([your size here])
Based on index use your variable..
yourlist[0] yourlist[1]....and so on
Hope this could help
Create list or arraylist
ArrayList<ArrayList<String>> group = new ArrayList<ArrayList<String>>(4);
or
List<List<String>> group1 = new ArrayList<List<String>>(4);
Edit:
ArrayList<String> list1 = new ArrayList<String>();
ArrayList<String> list2 = new ArrayList<String>();
To add (u can add items dynamically by loop)
group.add(list1);
and to get
list2= group.get(0);

How to convert a comma separated String to ArrayList in Java [duplicate]

This question already has answers here:
How to convert comma-separated String to List?
(28 answers)
Closed 9 years ago.
I have a comma separated String which i need to convert to ArrayList .
I tried this way
import java.util.ArrayList;
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
String CommaSeparated = "item1 , item2 , item3";
ArrayList<String> items = (ArrayList)Arrays.asList(CommaSeparated.split("\\s*,\\s*"));
for(String str : items)
{
System.out.println(str);
}
}
}
Its giving me the Runtime Error as shown
Exception in thread "main" java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList
at com.tradeking.at.process.streamer.Test.main(Test.java:14)
as i was trying to convert an List to arrayList by force .
The ArrayList returned by Arrays.asList is not java.util.ArrayList. It's java.util.Arrays.ArrayList. So you can't cast it to java.util.ArrayList.
You need to pass the list to the constructor of java.util.ArrayList class:
List<String> items = new ArrayList<String>(Arrays.asList(CommaSeparated.split("\\s*,\\s*")));
or, you can simply assign the result:
List<String> items = Arrays.asList(CommaSeparated.split("\\s*,\\s*"));
but mind you, Arrays.asList returns a fixed size list. You cannot add or remove anything into it. If you want to add or remove something, you should use the 1st version.
P.S: You should use List as reference type instead of ArrayList.
You can't just cast objects around like they're candy. Arrays.asList() doesn't return an ArrayList, so you can't cast it (it returns an unmodifiable List).
However you can do new ArrayList(Arrays.asList(...));
Does it absolutely need to be an ArrayList? Typically you want to use the most generic form. If you're ok using a List just try:
List<String> items = Arrays.asList(...);
You can still iterate over it the same way you currently are.
Please try to use bellow code.
String[] temp;
/* delimiter */
String delimiter = ",";
/*
* given string will be split by the argument delimiter provided.
*/
temp = parameter.split(delimiter);
ArrayList<String> list = new ArrayList<String>();
for (int l = 0; l < temp.length; l++)
{
list.add(temp[l]);
}
String CommaSeparated = "item1 , item2 , item3";
ArrayList<String> items = new ArrayList(Arrays.asList(CommaSeparated.split("\\s*,\\s*")));
for(String str : items)
{
System.out.println(str);
}

Why can't you have a "List<List<String>>" in Java? [duplicate]

This question already has answers here:
Is List<Dog> a subclass of List<Animal>? Why are Java generics not implicitly polymorphic?
(19 answers)
Closed 5 years ago.
In Java, why doesn't the following line of code work?
List<List<String>> myList = new ArrayList<ArrayList<String>>();
It works if I change it to
List<ArrayList<String>> myList = new ArrayList<ArrayList<String>>();
At first, I thought maybe you can't have lists of an interface, but I can create a List<Runnable> just fine.
Ideas?
Generic types are more pedantic.
List means List or any sub-type, but <List> means only List. If you want a sub-type you need to have <? extends List>
I suspect you can use
List<List<String>> myList = new ArrayList<List<String>>();
The reason you can't do this is that you can be using a reference to a reference and with an extra level of indirection you have to be careful.
// with one level of indirection its simple.
ArrayList alist = new ArrayList();
List list = aList; // all good
list = new LinkedList(); // alist is still good.
With generics you can have two level of indirection which can give you problems so they are more pedantic to avoid these issues.
// with two levels of indirection
List<ArrayList> alist = new ArrayList<ArrayList>();
List<List> list = (List) alist; // gives you a warning.
list.add(new LinkedList()); // adding a LinkedList into a list of ArrayList!!
System.out.println(alist.get(0)); // runtime error
prints
Exception in thread "main" java.lang.ClassCastException: java.util.LinkedList
cannot be cast to java.util.ArrayList
Lets start with this:
ArrayList<ArrayList<String>> myList = new ArrayList<ArrayList<String>>();
This is creating an ArrayList whose elements are ArrayLists.
Now suppose we could assign that to
List<List<String>> myList2 = myList.
Now, we should be able to do this:
myList2.add(new LinkedList<String>());
But that means we have added a LinkedList to a list whose elements are supposed to be ArrayLists. Ooops!!!
In reality, the assignment of myList to myList2 is not legal ... and that ensures that it is not possible to add the wrong kind of List<String> to the ArrayList<ArrayList<String>> object. (No Peter, it is not just pedantry :-) )
Only the top level collection can be declared as an implementing class, while the nested ones must remain interfaces until you actually create instances:
List<List<String>> rootList = new ArrayList<List<String>>();
and then when you create an element to go in, you make it an implementation:
List<String> nodeList = new ArrayList<String>();
rootList.add(nodeList);
Its comparing Type from left(declaration) side to Type from right(instantiation) side. In Left, your type is List<String> while in right, it's ArrayList<String>. If complaining about the difference.
Please update the right side(instatiation) as List i.e.
List<List<String>> myList = new ArrayList<List<String>>();
This should work fine.
I know this is an old question but I just wanted to share my idea.
Instead of making a List of Lists, I personally just make a List of Type[] (List<Type[]> listArray = new ArrayList<Type[]>();), I generate a separate List of just Type (List<Type> list = new ArrayList<Type>();), then .add(list.toArray()). This way, it's clearer and easier to read than the List of Lists syntax which is confusing.
For example, in a recent project where I had an input file where each line with only a "0" meant a new line in the original (it was an encryption algorithm):
String[] input = getInputContents(inFile);
List<String> currentBuffer = new ArrayList<String>();
List<String[]> buffers = new ArrayList<String[]>();
for(String line : input) {
if(line.equals("0")) {
buffers.add((String[])currentBuffer.toArray());
currentBuffer = new ArrayList<String>();
} else {
currentBuffer.add(line);
}
}
the list<list<string>> l1=new list<list<string>>(); is allowed if the list contains one more list inside the list.
public final class CPanelXMLBuilder extends PanelXMLBuilder {
public CPanelXMLBuilder(AuthenticatedUser pAuthenticatedUser, Map<String, Object> pSessionMap, Map<String, Object> pRequestMap, String pPanelTemplate) throws Exception {
super(pAuthenticatedUser, pSessionMap, pRequestMap, pPanelTemplate, null);
}
public Map<String, Object> buildXMLDocument(List<List<String>> pDetailsList) {
if (pDetailsList.size() == 1) {
List<String> pCustomerDetail = pDetailsList.get(0);
xmlDocument.getRootElement().getChild("E_SHOW1").setText(pCustomerDetail.get(0));
xmlDocument.getRootElement().getChild("E_SHOW2").setText(pCustomerDetail.get(1));
xmlDocument.getRootElement().getChild("E_SHOW3").setText(pCustomerDetail.get(2));
xmlDocument.getRootElement().getChild("E_SHOW4").setText(pCustomerDetail.get(3));
xmlDocument.getRootElement().getChild("E_SHOW5").setText(pCustomerDetail.get(4));
xmlDocument.getRootElement().getChild("ServerTimestamp").setText(pCustomerDetail.get(5).substring(0, 19));
} else {
xmlDocument.getRootElement().getChild("AlertType").setText("INFO");
xmlDocument.getRootElement().getChild("Alert").setText("There is no matching record.");
}
requestMap.put(RequestMapKeys.XML_DOCUMENT, xmlDocument);
return requestMap;
}
}

ArrayList to a String Array

Given 3 variables (homeNumber,mobileNumber and workNumber), which can be null, but atleast one of those will be a String, I need to return a String array so I can use it later on an Android Dialog. I'm having troubles doing this. I tried doing it in an ArrayList and removing all null elements, which leaves an ArrayList with only Strings, like I want, but when trying to change it to an Array I get a ClassCast exception on the last line.
ArrayList numberList = new ArrayList();
numberList.add(homeNumber);
numberList.add(mobileNumber);
numberList.add(workNumber);
numberList.removeAll(Collections.singleton(null));
final String[] items= (String[]) numberList.toArray();
Any ideas how to fix this?
String[] items = new String[numberList.size()];
numberList.toArray(items);
You can do one of two things:
Pass in the type of array you want to get (there's no need to instantiate a full length array, performance is the same regardless):
final String[] items= (String[]) numberList.toArray(new String[0]);
However, the better solution is to use generics:
List<String> numberList = new ArrayList<String>();
final String[] items= (String[]) numberList.toArray();
The return type of ArrayList.toArray() is Object[], unless you pass an array as the first argument. In that case the return type has the same type as the passed array, and if the array is large enough it is used. Do this:
final String[] items= (String[])numberList.toArray(new String[3])
Use the other method toArray() of List class:
numberList.toArray(new String[numberList.size()]);
Change
ArrayList numberList = new ArrayList();
to
List<String> numberList = new ArrayList<String>();

Categories