I'm just unsure why this isn't working.
ArrayList<String> test1 = new ArrayList<String>();
String[] input = new String[]{"biggest", "next", "not"};
test1.add(input);
there's an error in the 3rd line, at add.
My editor just says the symbol cannot be resolved, and just for the test, I typed test1. and ctrl + spaced it to see what it would give me, but no suggestion.
Any help?
by using add you can just add to the list what you defined in your generic, which would be String in your case. This isnĀ“t valid since you try to add an array of String to your list. to achive this you could us the addAll function like this.
ArrayList<String> test1 = new ArrayList<String>();
String[] input = new String[]{"biggest", "next", "not"};
test1.addAll(Arrays.asList(input));
Try This: ( Use Arrays.asList() )
String[] input = new String[]{"biggest", "next", "not"};
ArrayList<String> test1 =new ArrayList (Arrays.asList(input));
System.out.println(test1);
Or u can use this
List<String> test1 =new ArrayList ();
String[] input = new String[]{"biggest", "next", "not"};
Collections.addAll(test1, input);
System.out.println(test1);
Output:
[biggest, next, not]
Your arraylist is of type "String" , and you are trying to add a "String [ ]" object , you can't do that
if your list is like this
ArrayList<String[]> test1 = new ArrayList<String[]>();
that's will work you can add the array input as an object
Related
I am trying to read this line in Java - "abc:300:xyz:def", and I'm really unsure how to do this using arrays because in the array format it would be like this: ["abc:300:xyz:def"] . I started with
ArrayList<String> list = new ArrayList<String>();
list.add("abc");
list.add("300");
list.add("xyz");
list.add("def");
in my constructor, but then I don't know if I add a
list.split(":")
somewhere, because if so would that be right after I initialize the ArrayList?
Any help would be appreciated!
To join the items, use String.join
ArrayList<String> list = new ArrayList<>();
list.add("abc");
list.add("300");
list.add("xyz");
list.add("def");
String str = String.join(":", list);
To split the items, use String.split
ArrayList<String> list = Arrays.asList(str.split(":"));
Do this:
String line = "abc:300:xyz:def";
List<String> list = Arrays.asList(line.split(":"));
Now you have a list containing the 4 strings.
If you have to read a line from console you can try something like this
Scanner scanner = new Scanner(System.in);
String yourString = scanner.next();
StringTokenizer st = new StringTokenizer(yourString , ":");
while (st.hasMoreElements()) {
System.out.println(st.nextElement());
}
If you are looking only the arrays not the arraylist, you can just use the split method from the string
String line = "abc:300:xyz:def";
String[] stringArray = line.split(":");
subjectList = [ITC102 Coding , ITC106 Programming , ITC206 Java , MGT100 Management]
This is the arraylist that i want to split into two sub arraylist.
I want to make two new arrays subCode and subName.
subcode = [ITC102 , ITC106 , ITC206 , MGT100]
subName = [Coding , Programming , Java , Management]
I tried .sublist but it sublists the whole list instead of the data inside each list.
If in every record there are only two words separated by space then you can do something like below:
List<String> list =new ArrayList<String>();
list.add("ITC102 Coding");
list.add("ITC106 Programming");
list.add("ITC206 Java");
list.add("MGT100 Management");
List<String> subcode =new ArrayList<String>();
List<String> subName =new ArrayList<String>();
for(String str:list)
{
String strArray[]=str.split(" ");
subcode.add(strArray[0]);
subName.add(strArray[1]);
}
I get a coding error in eclips Type mismatch, cannot convert Object to String. All data going into AL is String Type and AL is declared as String.
If i can just have AL go to a String[] that would be better.
heres my code:
Object[] Result;
AL.toArray (Result);
String[] news= new String[Result.length];
for (int i1=0;i1<news.length;i1++){
news[i1]=Result[i1]; <=====here is where the error shows up
Change this:
news[i1]=Result[i1];
to this:
news[i1]=Result[i1].toString();
Try type casting.
news[i1] = (String) Result[i1];
However, it is probably a good idea to check the type of Result[i1] before type casting like that. So you could do something like
if( Result[i1] instanceof String){
news[i1] = (String) Result[i1];
}
If you are absolutely sure that every object in Result array is String type, why don't you use String[] in the first place? Personally, I'm not a big fan of Object[]...
String[] stringArray = Arrays.copyOf(objectArray, objectArray.length, String[].class);
You can supply the ArrayList.toArray() method with an existing array to define what type of array you want to get out of it.
So, you could do something like this:
String[] emptyArray = new String[0];
String[] news = AL.toArray(emptyArray);
Try this code:
public static void main(String[] args)
{
Object[] Result = {"a1","a2","a3"};
String[] AL = new String[Result.length];
for(int a=0; a<Result.length; a++)
{
AL[a] = Result[a].toString();
}
System.out.println(AL[0]);
System.out.println(AL[1]);
System.out.println(AL[2]);
}
Since AL is, as you report, an ArrayList<String>, this should do what you want in one line of code:
String[] news = AL.toArray(new String[AL.size()]);
In my String, I can have an arbitrary number of words which are comma separated. I wanted each word added into an ArrayList. E.g.:
String s = "a,b,c,d,e,.........";
Try something like
List<String> myList = new ArrayList<String>(Arrays.asList(s.split(",")));
Arrays.asList documentation
String.split documentation
ArrayList(Collection) constructor documentation
Demo:
String s = "lorem,ipsum,dolor,sit,amet";
List<String> myList = new ArrayList<String>(Arrays.asList(s.split(",")));
System.out.println(myList); // prints [lorem, ipsum, dolor, sit, amet]
This post has been rewritten as an article here.
String s1="[a,b,c,d]";
String replace = s1.replace("[","");
System.out.println(replace);
String replace1 = replace.replace("]","");
System.out.println(replace1);
List<String> myList = new ArrayList<String>(Arrays.asList(replace1.split(",")));
System.out.println(myList.toString());
In Java 9, using List#of, which is an Immutable List Static Factory Methods, become more simpler.
String s = "a,b,c,d,e,.........";
List<String> lst = List.of(s.split(","));
Option1:
List<String> list = Arrays.asList("hello");
Option2:
List<String> list = new ArrayList<String>(Arrays.asList("hello"));
In my opinion, Option1 is better because
we can reduce the number of ArrayList objects being created from 2 to 1. asList method creates and returns an ArrayList Object.
its performance is much better (but it returns a fixed-size list).
Please refer to the documentation here
Easier to understand is like this:
String s = "a,b,c,d,e";
String[] sArr = s.split(",");
List<String> sList = Arrays.asList(sArr);
Ok i'm going to extend on the answers here since a lot of the people who come here want to split the string by a whitespace. This is how it's done:
List<String> List = new ArrayList<String>(Arrays.asList(s.split("\\s+")));
If you are importing or you have an array (of type string) in your code and you have to convert it into arraylist (offcourse string) then use of collections is better. like this:
String array1[] = getIntent().getExtras().getStringArray("key1"); or String array1[] = ... then
List allEds = new ArrayList(); Collections.addAll(allEds, array1);
You could use:
List<String> tokens = Arrays.stream(s.split("\\s+")).collect(Collectors.toList());
You should ask yourself if you really need the ArrayList in the first place. Very often, you're going to filter the list based on additional criteria, for which a Stream is perfect. You may want a set; you may want to filter them by means of another regular expression, etc. Java 8 provides this very useful extension, by the way, which will work on any CharSequence: https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html#splitAsStream-java.lang.CharSequence-. Since you don't need the array at all, avoid creating it thus:
// This will presumably be a static final field somewhere.
Pattern splitter = Pattern.compile("\\s+");
// ...
String untokenized = reader.readLine();
Stream<String> tokens = splitter.splitAsStream(untokenized);
If you want to convert a string into a ArrayList try this:
public ArrayList<Character> convertStringToArraylist(String str) {
ArrayList<Character> charList = new ArrayList<Character>();
for(int i = 0; i<str.length();i++){
charList.add(str.charAt(i));
}
return charList;
}
But i see a string array in your example, so if you wanted to convert a string array into ArrayList use this:
public static ArrayList<String> convertStringArrayToArraylist(String[] strArr){
ArrayList<String> stringList = new ArrayList<String>();
for (String s : strArr) {
stringList.add(s);
}
return stringList;
}
Let's take a question : Reverse a String. I shall do this using stream().collect(). But first I shall change the string into an ArrayList .
public class StringReverse1 {
public static void main(String[] args) {
String a = "Gini Gina Proti";
List<String> list = new ArrayList<String>(Arrays.asList(a.split("")));
list.stream()
.collect(Collectors.toCollection( LinkedList :: new ))
.descendingIterator()
.forEachRemaining(System.out::println);
}}
/*
The output :
i
t
o
r
P
a
n
i
G
i
n
i
G
*/
This is using Gson in Kotlin
val listString = "[uno,dos,tres,cuatro,cinco]"
val gson = Gson()
val lista = gson.fromJson(listString , Array<String>::class.java).toList()
Log.e("GSON", lista[0])
I recommend use the StringTokenizer, is very efficient
List<String> list = new ArrayList<>();
StringTokenizer token = new StringTokenizer(value, LIST_SEPARATOR);
while (token.hasMoreTokens()) {
list.add(token.nextToken());
}
If you're using guava (and you should be, see effective java item #15):
ImmutableList<String> list = ImmutableList.copyOf(s.split(","));
paramList = new ArrayList<String>();
paramList.add(line.split(","));
When I used this, it gives me the error:
cannot find symbol
symbol: method add(java.lang.String[])
location: interface java.util.List<java.lang.String>
With this, I would get output in this manner: "abc" "bvc" "ebf" . Now can I use trim to get rid of " ". So that the output becomes: abc bvc ebf
Input: "AAH196","17:13:00","02:49:00",287,166.03,"Austin","TX","Virginia Beach","VA"
Output: AAH196 17:13:00 02:49:00 287 166.03 Austin TX Virginia Beach VA
I need to remove the " "around the words and , between the words. I want to store this output and then jdbc will parse this data into the tables of my database on mysql.
paramList.add() wants a String but line.split(",") returns String[]
The two are not equivalent.
Maybe you want something like:
paramList = Array.asList(line.split(","));
or
paramList = new ArrayList<String>();
for(String s : line.split(",")){
paramList.add(s);
}
As for the added question, there are lots of ways to skin a cat.
If the words are ALWAYS surrounded by quotes then you can do something like:
paramList = new ArrayList<String>();
for(String s : line.split(",")){
paramList.add(s.substring(1, s.length());
}
This will remove the first and last char from the String. Which will always be the quotes.
If you need something more flexible (For instance this solution would ruin string that aren't surrounded by quotes) then you should read up on regex and java's Pattern class to see what suites your needs.
As for the solution that you provided, trim() will only remove surrounding whitespace.
import java.util.ArrayList;
class TestGenericArray {
public static void main(String[] args) {
String[] stringArray = {"Apple", "Banana", "Orange"};
ArrayList<String[]> arrayList = new ArrayList<String[]>();
arrayList.add(stringArray);
}
}