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(","));
Related
if(CoverageNames.size()>0) {
StringBuffer tmp = new StringBuffer();
for(int i =0; i<CoverageNames.size();i++) {
tmp.append(CoverageNames.get(i).getText());
tmp.append(";");
}
List<String[]> covNamesListReport= new ArrayList<>();
String[] CoverageNamesListReport={"CoverageNamesListReport",tmp.toString()};
covNamesListReport.add(CoverageNamesListReport);
String CovName= covNamesListReport.toString();
CoverageReportList("CoverageNames", CovName);
}
Coverage Report List is a method that accepts two string arguments.
I'm learning right now so any other approaches are also welcome.
When converting List<String[]> to string in line covNamesListReport.toString();, the contents of the inner arrays is NOT displayed as expected and look like [[Ljava.lang.String;#726f3b58] because the arrays' toString method is invoked.
To display the contents of the inner strings properly, nested List<String> could be used:
List<List<String>> covNamesListReport = new ArrayList<>();
List<String> CoverageNamesListReport = Arrays.asList("CoverageNamesListReport", tmp.toString());
covNamesListReport.add(CoverageNamesListReport);
String CovName = covNamesListReport.toString();
// -> [[CoverageNamesListReport, AAA;BB;CCC;]]
or Arrays.toString could be used just to convert a nested array:
List<String> covNamesListReport= new ArrayList<>();
String CoverageNamesListReport= Arrays.toString(new String[] {
"CoverageNamesListReport", tmp.toString()
});
covNamesListReport.add(CoverageNamesListReport);
String CovName= covNamesListReport.toString();
// -> [[CoverageNamesListReport, AAA;BB;CCC;]]
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(":");
Is it possible to split a string into an string array that hasn't been declared?
I want to add a string array to a list, so currently I have it set like this vars.add(new String[]{s}); where s is a string. Is there anyway to make it add s.split("|")?
Or is the only option:
String [] ns = s.split("|");
vars.add(ns);
I was playing in netbeans, where I would this make a string array, with this string "A|C|D|E":
new String(s).split("|");
Is this what you're looking for?
ArrayList<String[]> vars = new ArrayList<String[]>();
String s = "A|C|D|E";
vars.add(s.split("\\|"));
Note that if you want to add the Strings individually to the list, you must do it slightly differently.
ArrayList<String> vars = new ArrayList<String>();
String s = "A|C|D|E";
for (Sting str : s.split("\\|"))
vars.add(str);
I converted the ArrayList<String> list which contains "String1", "String2" to String by using list.toString(). The resulted string format is [String1, String2]. Is there any way to convert this result back to ArrayList<String>?
Try applying the following code
String value = "[String1,String2,String3]";
value = value.subString(1,value.length()-1);
String[] split = value.split(",");
List<String> sampleList = Arrays.asList(split);
create a new Class extending Array List
public class CustomArrayList<Item> extends ArrayList<Item> {
and override
toString
method, which could give a comma separated String representation.
Now use
new CustomArrayList<Item>(Arrays.asList(list.toString().split(",")))
to get it back in ArrayList.
No direct way. Just get that String remove those [] from String and then split by , then add back to list.
Something like this,considering the given format.
String s = "[String1, String2]";
s = s.substring(1, s.length() - 1);
List<String> list = new ArrayList<>();
for (String string : s.split(",")) {
list.add(string.trim());
}
I have a array list in which I bind the data
This is a example
MyStrings =new ArrayList<String>();
MyStrings.add("Dog");
MyStrings.add("Cat");
MyStrings.add("Can");
MyStrings.add("Ant");
MyStrings.add("Str");
Now I have a string String sweet="c";
Now what OI want is to filter that Arraylist based on my string(sweet)
so the items of the MyStrings will be only Cat and Can
EDIT
I am really sorry for the trouble I got you but my main problem is that sweet is a editable
Ive tried using this code
public void onTextChanged(CharSequence s, int start, int before,int count) {
//adapter2.getFilter().filter(s);
//int length = filterEditText.getText().length();
filterME = filterEditText.getText();
List<String> MySortStrings =new ArrayList<String>();
for(int i=0;i<MyStrings.size();i++)
{
String newString = MyStrings.get(i);
if (newString.startsWith(filterME)){
}
}
//adapter2 = new LazyAdapterGetFriends(MyFriends.this,x);
//list.setAdapter(adapter2);
}
using this declaration
LazyAdapterGetFriends adapter2;
ArrayList<String> MyStrings;
//List<String> MyStrings;
EditText filterEditText;
Sorry for my wrong question..
Foolish me
List<String> MyStrings =new ArrayList<String>();
List<String> MySortStrings =new ArrayList<String>();
MyStrings.add("Dog");
MyStrings.add("Cat");
MyStrings.add("Can");
MyStrings.add("Ant");
MyStrings.add("Str");
String sweet="c";
for(int i=0;i<MyStrings.size();i++)
{
if(MyStrings.get(i).startsWith(sweet.toUpperCase()))
{
MySortStrings.add(MyStrings.get(i));
}
}
System.out.println(MySortStrings.size());
The list MySortStrings contains the Cat & Can
These days you can also use streams to do it easily:
stringList.stream().filter(s -> s.contains("c")).collect(Collectors.toList())
When you would only need to know if there is a string in the list containing your letter (not part of the question but very useful) you can do this:
stringList.stream().anyMatch(s -> s.contains("c"))
Use str.startsWith(String, int index)
Index will tell you from which index in the str it should start comparing
The naive algorithm will be that you just filter everything out like this:
ArrayList<String> filtered = new ArrayList<String>();
for(String s : MyStrings){
if(s.substring(0,1).toLowerCase().equals("c")){
filtered.add(s);
}
}
but then you have access time in O(n).
if you need a more faster way you probably need to use a Key,Value Structure with Key set to the String you need to filter. Or even a http://en.wikipedia.org/wiki/Trie, where you can easily filter on every character in the string. But then you will need extra time in building up this thing.
Okay, this should be it when using your TextWatcher Stuff (untested...)
private List<String> MySortStrings = new ArrayList<String>(); // assume that your data is in here!
private List<String> MySortedStrings = new ArrayList<String>(); // this will be the list where your sorted strings are in. maybe you could also remove all strings which does not match, but that really depends on your situation!
public void onTextChanged(CharSequence s, int start, int before,int count) {
for(String str : MySortStrings){
if(str.startsWith(s.toString()){
MySortedStrings.add(str);
}
}
}
If you want to remove items that don't match from MyStrings rather than create a new ArrayList you will need to use an Iterator as this is the only safe way to modify a ArrayList while iterating over it.
myStrings = new ArrayList<String>();
myStrings.add("Dog");
myStrings.add("Cat");
myStrings.add("Can");
myStrings.add("Ant");
myStrings.add("Str");
String sweet="c";
sweet = sweet.toLowerCase();
Iterator<String> i = myStrings.iterator();
while (i.hasNext()) {
if (! i.next().toLowerCase().startsWith(sweet)) {
i.remove();
}
}
You can use the apache commons-collections library as well:
CollectionUtils.filter(myStrings,
new Predicate() {
public boolean evaluate(Object o) {
return ! ((String)o).startsWith("c");
}
}
};
Any object for which the "evaluate" method of the Predicate class returns false is removed from the collection. Keep in mind, that like the solution above using the Iterator, this is destructive to the list it is given. If that is an issue, you can always copy the list first:
List<String> filtered = new ArrayList<String>(myStrings);
CollectionUtils.filter(filtered, ...);