I have a string
String strNumbers = "One,Two,Three,Four,Five";
O want to split this string and produce
One
Two
Three
Four
Five
Help me out please.
I am using following code
String strNumbers = "One,Two,Three,Four,Five";
//split the string using split method of String class
String[] numbers = strNumbers.split(",");
//create new ArrayList object
ArrayList<String> aListNumbers = new ArrayList<String>();
//add individual numbers to the ArrayLists
for(int i=0; i< numbers.length; i++){
aListNumbers.add(numbers[i]);
}
List<String> aListNumbers = new ArrayList<String>(
Arrays.asList(strNumbers.split(","));
split gives you an array. Arrays.asList wraps a list around an array.
If you really need an ArrayList, you can then use its ArrayList(Collection) copy constructor.
Right now you're just printing out the ArrayList object. You need to iterate through the ArrayList and print out the String values it contains. You can do this with System.out.println, which will automatically put a new line after each value it prints.
for (String number : aListNumbers) {
System.out.println(number);
}
Related
String [] TxtStr = new String[] {"bob","alan", "sam"};
List<String> stringList = new ArrayList<String>(Arrays.asList(TxtStr));
String [] TxtStr2 = new String[] {"bob","alan"};
List<String> stringList2 = new ArrayList<String>(Arrays.asList(TxtStr));
stringList.removeAll(stringList2);
String[] bTxtStr = stringList.toArray(new String[stringList.size()]);
String output = "nnn";
for (int x=0; x<bTxtStr.length; x++){
output +=bTxtStr[x];
}
Currently this is a small segment of an android project I'm working on where I have to compare the contents of 2 String[].
I've been having quite a few problems so I've started out with a simple case of 2 String[] with 2 and 3 elements respectively. After initializing the String[] I convert them to ArrayLists and perform the removeAll function, which ideally should remove the elements "bob" and "alan" from the first list and eventually the output.
BTW using remove to stringList.remove("bob") works in terms of eliminating that particular string from the ArrayList. Just wondering what I can do to ensure that stringList.removeAll(....) works.
Thanks for any help in advance.
you have bug in:
List<String> stringList2 = new ArrayList<String>(Arrays.asList(TxtStr));
you should use TxtStr2:
List<String> stringList2 = new ArrayList<String>(Arrays.asList(TxtStr2));
reomoveAll method of ArrayList definitely works fine. You have made mistake while creating second ArrayList.
For easy approach, you can use Java 8 Streams. Try the below code. It will give you directly single comma separated string. You can change separation character.
List<String> stringList = Arrays.asList("bob","alan", "sam");
List<String> stringList2 = Arrays.asList("bob","alan");
String mergedString = stringList.stream().filter(string ->!stringList2.contains(string)).collect(Collectors.joining(","));
System.out.println("Merged String: " + mergedString);
You might be ending up removing everything, because of your list creation which are based on same arrays. Change
List<String> stringList2 = new ArrayList<String>(Arrays.asList(TxtStr);
to
List<String> stringList2 = new ArrayList<String>(Arrays.asList(TxtStr2);
I am looking for a solution how I can get an array of contains from another one.
For example:
I have an array:
Array= [S1!!T1, S1!!T2, S1!!T3, S2!!T1, S2!!T2, S3!!T1, S3!!T2, S3!!T3]
I am looking for elements in "Array" that contain "S2" and write them to another one. so i should get:
Result = [S2!!T1, S2!!T2]
I already tried the Arrays.asList(I).contains(i) but this is not what i am lookig for i think.
If you wish to copy elements of one array to another, first thing you need to do is loop through the elements of one array and if you find a match then store it into another array.
Let's say you have the following array:
String[] arr = new String[]{"S1!!T1", "S1!!T2", "S1!!T3", "S2!!T1", "S2!!T2", "S3!!T1", "S3!!T2", "S3!!T3"};
We don't know how many of those elements in the array are going to match until we loop through them so we have two choice:
Create another array with the same size as arr (cause some null values in array if not all entries of arr re matched)
Use ArrayList and then later convert ArrayList to array if needed
See below:
public static void main(String[] args) {
String[] arr = new String[]{"S1!!T1", "S1!!T2", "S1!!T3", "S2!!T1", "S2!!T2", "S3!!T1", "S3!!T2", "S3!!T3"};
List<String> s2List = new ArrayList<String>();
//loop through arr and for each element check if it contains S2
for(int i = 0; i < arr.length; i++) {
//if it contains S2 then it returns true and we add it to list
if(arr[i].contains("S2")) {
//add to list the element
s2List.add(arr[i]);
}
}
//print the list for testing
System.out.println(s2List);
//if you wish to store the elements to array then
//now we know how many matched, so we can create array with the
//size of elements in s2List
String[] sArr = new String[s2List.size()];
//Here loop through the list and assign values to array
for(int i = 0; i < s2List.size() ; i++) {
sArr[i] = s2List.get(i);
}
//print the array
System.out.println(Arrays.toString(sArr));
}
You can also use other methods that convert a List to array directly but, above should give you an idea of how to resolve the question you asked.
You could use Java 8 streams
String[] filtered = Stream.of(strings).filter(s -> s.contains("S2")).toArray(String[]::new);
I am reading from a text file and saving the lines into an ArrayList. But I have had no success in how to go through and read all of the specific characters in the ArrayList, how many columns and rows there are.
This is the code I have written so far:
String line;
BufferedReader br = new BufferedReader(r);
ArrayList<String> myArrayList = new ArrayList<String>();
while ((line = br.readLine()) != null)
{
myArrayList.add(line);
.........
}
If I am reading your post right you are wanting to further break apart your lines (your reference to columns). Since you are storing String objects you will need to further break apart those entries into another List to truly parse through your words and characters appropriately.
Java used to have something called the StringTokenizer which could do what you want but that is now deprecated and replaced by the String.Split() method. By iterating through your ArrayList and splitting the String Object by specific delimiters (such as a space or a period), you should be able to further breakdown your existing ArrayList and create a new List with individual words, or even characters.
I do not know why you use "store.add(line)". You should use myArrayList instead of this.
After you have stored everything in the ArrayList you can use a for-each loop to traverse through the list:
for (String string : myArrayList) {
// do everything with the strings here
}
You aren't calling the List myArrayList, I think you want to change this
ArrayList<String> myArrayList = new ArrayList<String>();
to (using the diamond operator and the interface type) -
List<String> store = new ArrayList<>(); // <-- match the name.
You can count the "rows" by getting the size of the List -
int rows = store.size();
To count "columns" you would need to iterate the List and examine the lines. (or you could do that while you read the input) -
for (String line : store) {
// count columns in line
}
If you want to go through a ArrayList there are many ways that you can try
You can easily get number of elements in the ArrayList using size() method.
e.g.
//traditional way
for(int i = 0; i< arrayList.size(); i++){
System.out.println(arrayList.get(i));
}
//enhanced forloop
if your ArrayList is String type
for(String row : arrayList)
System.out.println(row);
With Java 8 you cane have more easier iterator that can use to go through the ArrayList
Edited
If you wanna read character by character
for(String row : arrayList){
char []letters = row/toCharArray();
for(char character : letters)
System.out.print(character + " ") ;
}
I know there is a String split method that returns an array but I need an ArrayList.
I am getting input from a textfield (a list of numbers; e.g. 2,6,9,5) and then splitting it at each comma:
String str = numbersTextField.getText();
String[] strParts = str.split(",");
Is there a way to do this with an ArrayList instead of an array?
You can create an ArrayList from the array via Arrays.asList:
ArrayList<String> parts = new ArrayList<>(
Arrays.asList(textField.getText().split(",")));
If you don't need it to specifically be an ArrayList, and can use any type of List, you can use the result of Arrays.asList directly (which will be a fixed-size list):
List<String> parts = Arrays.asList(textField.getText().split(","));
There is no such thing as a Split functionfor list, but you can do the split and then convert to a List
List myList = Arrays.asList(myString.split(","));
This question already has answers here:
Looping in ArrayLists with a Method
(3 answers)
Closed 9 years ago.
I have a java program that
reads a text file,
puts all it's words in an ArrayList
puts all the words into an ArrayList, lowercase with punctuation removed
I now want to make two more things.
A function that creates all the anagrams of the strings of a String ArrayList,
an ArrayList of ArrayLists that will store each of the anagrams and the original string into each ArrayList in the ArrayList.
So I want to develop a function that will take a string that I am inserting from one ArrayList into a new ArrayList and make all it's anagrams and put them in an ArrayList and then put that ArrayList in the ArrayList that is reading the old ArrayList.
Something that will look like this:
List<String> arLists = new ArrayList<String>(); //makes new array list
for(String arList : words) //takes values from old array list
ArrayList<String> anaLists = new ArrayList<String>(); //makes a new array list
arLists.add(anag(anaLists,arList,"")); //uses a function that makes an
I want to make a function kinda like this, but what I have made here... doesn't really work.
public void anag(ArrayList<String> anaLists, String s1, String s2){
if(s1.length() == 0){
return anaLists;
}
for(int i = 0 ; i < s1.length() ; i++){ //only runs for string length
String anaList = anag(s1.substring(0, i) + s1.substring(i+1, s1.length()), s1.charAt(i) + s2);
anaLists.add(anaList);
}
}
Some guidance on this would be superb.
To make all anagrams from a string, follow the following steps:
Step 1: Use String's replace to remove whitespace, and make sure all punctuation and capitalization has been removed.
Step 2: Write this function f(string s, string anagram, ArrayList<String> array) and call it with s = yourstring, anagram = "", array = new ArrayList<String>():
If s is empty, add anagram to array and return
For each letter l in s:
newanagram = anagram + l
news = s with l taken out of it (e.g. make a substring of everything before l in s and everything after l in s, and concatenate them together)
call f(news, anagram, array)
This will explore a 'tree' of recursive self calls, and at each 'leaf' of the 'tree' each possible permutation of all the letters will be added to the array. When it finishes, n*n-1*n-2*n-3... aka n factorial entries will be in the array, which is how you know you're on the right track :)
And if you need an anagram of every string in an arraylist, just call it in a for loop.
After some struggle, I have tried to understand your question and here's my answer. Correct me if I am wrong. First of all, you can do all that pre-processing stuff like changing case, removing grammar using one array list. Now to the actual function:
public void getAnag(String baseStr, ArrayList<String> finalAnagList)
{
ArrayList<String> anagList = new ArrayList<String>();
anagList = getAnagrams(baseStr); // getAnagrams is a support function to get the anagrams
anagList.add(baseStr); // I suppose you want to add the base string also to the anagrams list
finalAnagList.add(anagList);
}
And your calling function in program would be:
public void testAnagrams()
{
ArrayList<String> words = getWordsFromFile("/home/list.txt"); // gets the words from the file
ArrayList<String> anagramsList = new ArrayList<String>();
foreach(String word : words)
{
getAnag(word, anagramsList);
}
}