How to split strings of list into string array - java

I have a list that contains ("One.two.three", "one.two.four"). I want to save then in a string array as
One
two
three
one
two
four
What is the logic behind it?

You should be using java 8 to run this code. Just take those strings and split them on "."
split method of java need regex so to match "." you need "\.".Then transform array to list, then add words to list.
public static void main(String[] args) {
List<String> words = new ArrayList<String>();
List<String> list = new ArrayList<String>();
list.add("One.two.three");
list.add("one.two.four");
list.stream().forEach(str -> {
words.addAll(Arrays.asList(str.split("\\.")));
});
System.out.println(words.toString());
//output : [One, two, three, one, two, four]
}

For java 8+, you can use flatmap as -
String[] words = list.stream().flatMap(str -> Arrays.stream(str.split("\\."))).toArray(String[]::new);

If you are talking about the static arrays it is important to know array size to avoid "index is out of bounds" exception.
This way, I provide the solution that counts the number of words and then creates output s array to save every word.
We can use the String.split() function to get the single words we adding to output array:
String[] a = {"One.two.three", "one.two.four"};
int count = 0;
for (int i = 0; i < a.length; i++) { //skip this loop if you know the wanted array size
count += a[i].split("\\.").length;
}
String[] s = new String[count];
int k = 0;
for (int i = 0; i < a.length; i++) {
String[] b = a[i].split("\\.");
for (int j = 0; j < b.length; j++) {
s[k++] = b[j];
}
}
for (int i = 0; i < s.length; i++) {
System.out.println(s[i]);
}

Try this.
FOR JAVA 1.8+
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("One.two.three");
list.add("One.two.four");
List<String> newList = new ArrayList<String>();
list.forEach(string -> {
String[] stringArr = string.split("\\.");
for (String innerString : stringArr) {
newList.add(innerString);
}
});
String[] stringArr = newList.toArray(new String[newList.size()]);
System.out.println(Arrays.toString(stringArr));
}
UPTO JAVA 1.7
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("One.two.three");
list.add("One.two.four");
List<String> newList = new ArrayList<String>();
for (String string : list) {
String[] stringArr = string.split("\\.");
for (String innerString : stringArr) {
newList.add(innerString);
}
}
String[] stringArr = newList.toArray(new String[newList.size()]);
System.out.println(Arrays.toString(stringArr));
}

If you are below Java 8 you can use this snippet:
public class Main {
public static void main(String[] args) throws Exception {
List<String> originalList = new ArrayList();
List<String> finalList = new ArrayList();
originalList.add("One.two.three");
originalList.add("One.two.four");
for(String myString : originalList) {
//The \\ is to scape the dot
finalList.addAll(Arrays.asList(myString.split("\\.")));
}
//Creates an array from the list
String[] theArray = finalList.toArray(new String[finalList.size()]);
}
}
Finally, theArray will contain:
[One, two, three, one, two, four]
Take a look at the docs about splitting an string into parts

Related

Java splitting string using delimiter and store to different array

I was having some problem when trying to split string with delimiter and store to array. So basically I have a main array with input like this:
1564095_SINGLE_true, 1564096_SINGLE_true
What I am trying to do is split the string with delimiter and store to two different array. Below as how I loop thru the main array:
String arrayA = [];
String arrayB = [];
for(int i = 0; i < selectedRecord.length; i++) {
log.debug("HEY " + selectedRecord[i]);
String tempRecord = selectedRecord[i];
}
My desired output will be:
arrayA: 1564095_SINGLE, 1564096_SINGLE
arrayB: true, true
But I have no idea on how to split it. Any ideas? Thanks!
Here is one approach which splits in the input on the following regex pattern:
_(?!.*_)
This splits the input string on only the last underscore character. We can try iterating your collection of inputs, and then populating the two arrays.
List<String> inputs = Arrays.asList(new String[] {"1564095_SINGLE_true", "1564096_SINGLE_true"});
String[] arrayA = new String[2];
String[] arrayB = new String[2];
int index = 0;
for (String input : inputs) {
arrayA[index] = input.split("_(?!.*_)")[0];
arrayB[index] = input.split("_(?!.*_)")[1];
++index;
}
System.out.println("A[]: " + Arrays.toString(arrayA));
System.out.println("B[]: " + Arrays.toString(arrayB));
This prints:
A[]: [1564095_SINGLE, 1564096_SINGLE]
B[]: [true, true]
Does this help? Assuming you can apply basic checks (null, array length, etc)
String[] selectedRecord = {"1564095_SINGLE_true", "1564096_SINGLE_true"};
String[] arrayA = new String[selectedRecord.length];
String[] arrayB = new String[selectedRecord.length];
for (int i = 0; i < selectedRecord.length; i++) {
arrayA[i] = selectedRecord[i].substring(0, selectedRecord[i].lastIndexOf("_"));
arrayB[i] = selectedRecord[i].substring(selectedRecord[i].lastIndexOf("_")+1);
}
System.out.println(Arrays.asList(arrayA));
System.out.println(Arrays.asList(arrayB));
check below code
import java.util.*;
public class MyClass {
public static void main(String args[]) {
String str="1564095_SINGLE_true, 1564096_SINGLE_true";
System.out.println(str);
String arr[]=str.split(",");
ArrayList<String> arr1=new ArrayList();
ArrayList<String> arr2=new ArrayList();
for(int i=0;i<arr.length;i++)
{
String temp[]= arr[i].split("_");
for(int j=0;j<temp.length;j++)
{
if(j==2)
{
arr2.add(temp[j]);
}
else
{
arr1.add(temp[j]);
}
}
}
System.out.println(arr1);
System.out.println(arr2);
}
}
String selectedRecord[] = { "1564095_SINGLE_true", "1564096_SINGLE_true" };
String[] arrayA = new String[selectedRecord.length];
String[] arrayB = new String[selectedRecord.length];
for(int i = 0; i < selectedRecord.length; i++) {
String tempRecord = selectedRecord[i];
int size = tempRecord.split("_").length;
arrayB[i]= tempRecord.split("_")[size-1];
arrayA[i]= tempRecord.replace("_"+arrayB[i], "");
}
System.out.println("ArrayA: "+ Arrays.asList(arrayA));
System.out.println("ArrayB: "+ Arrays.asList(arrayB));
Output:
ArrayA: [1564095_SINGLE, 1564096_SINGLE]
ArrayB: [true, true]
Hi you can do something like this. Get the last index of the delimiter and substring the string.
String arrayA = [];
String arrayB = [];
for(int i = 0; i < selectedRecord.length; i++) {
int end = selectedRecord.lastIndexOf("_");
arrayA[i] = selectedRecord.substring(0, end);
arrayB[i] = selectedRecord.substring(end+1);
}
Of course here should be some datatype conversions. If you want to store "true"/"false" inside of the boolean array.

How to get list of words from a list of lines in java?

If I have two lines, how can I split them into a list of two lists of words?
I tried the following code:
ArrayList<String> lines = [Hello World, Welcome to StackOverFlow];
List<String> words;
List<List<String>> listOfWords;
for (int i = 0; i < lines.size(); i++) {
words = Arrays.asList(lines.get(i).split(" "));
listOfWords = Arrays.asList(words);
}
System.out.println(listOfWords);
The output of the above code is
[[welcome, to, StackOverFlow]]
Can someone please help me to get the output as follows?
[[Hello, World], [Welcome, to, StackOverFlow]]
On every iteration of your for loop you are overwriting listOfWords by wrapping your latest words array in a new list. So effectively you will always just have your most recent line's list of words as the only item listOfWords.
To fix this modify following below the body of your for statement similar to the following:
public static void main(String[] args) {
String[] lines = {"Hello World", "Welcome to StackOverFlow"};
List<String> words;
List<List<String>> listOfWords = new ArrayList<List<String>>(); // Must be instantiated or you will get NullPointerException
for (int i = 0; i < lines.length; i++) {
words = Arrays.asList(lines[i].split(" "));
listOfWords.add(words); //Add to `listOfWords` instead of replace with a totally new one
}
System.out.println(listOfWords);
}
Some of the syntax was not correct so I fixed it. In that process I converted lines into an Array. Tested and confirmed output.
public static void main(String[] args) {
System.out
.println(splitStatementsIntoWords(new ArrayList<String>() {
{
add("Hello World");
add("Welcome to StackOverFlow");
}
}));
}
public static List<List<String>> splitStatementsIntoWords(List<String> statements) {
List<List<String>> result = new ArrayList<>();
if (statements != null) {
for (String statement : statements) {
result.add(Arrays.asList(statement.split("\\s+"))); // \\s+ matches one or more contigeous white space.
}
}
return result;
}

java : remove words from ArrayList<String>

lets say my words Array is words={"a","the","in","if","are","it","is"} and my ArrayList contains strings like this {"a table is here", "books are sold","if it is readable"}. i want to remove all the words of array from the arrayList.
expected output would be ArrayList as {"table here","books sold","readable"}.
i have tried this so far :
public static void main(String[] args) {
String[] words = {"a","the","in","if","are","it","is"};
List<String> wordList = new ArrayList<String>(Arrays.asList(words));
String[] tArray = {"a table is here", "books are sold","if it is readable"};
List<String> list = new ArrayList<String>(Arrays.asList(tArray));
for (int i = 0; i < list.size(); i++) {
String[] tArrays = list.get(i).split(" ");
List<String> line = new ArrayList<String>(Arrays.asList(tArrays));
for (int c = 0; c < wordList.size(); c++) {
if (wordList.get(c).equals(line.get(i))) {
line.remove(i);
i--;
break;
}
}//end for
list.set(i, String.join(" ", line));
}//end for
for(String string : list)
{
System.out.println(string);
}
}
but not giving the expected output. instead gives an error "java.lang.ArrayIndexOutOfBoundsException: -1"
You should be using line.size() to iterate for all the words after splitting based on " ".
for (int i = 0; i < list.size(); i++) {
String[] tArrays = list.get(i).split(" ");
List<String> line = new ArrayList<>(Arrays.asList(tArrays));
for (int c = 0; c < wordList.size(); c++) {
if (wordList.get(c).equals(line.get(i))) { // you get i for indexes corresponding to the sentence element and not `line` elements as created above
line.remove(i); // i is iterated over the list of sentences in your case 3, would start from i=0
i--; // you change it to '-1' and get IndexOutOfBounds
break;
}
}//end for
list.set(i, String.join(" ", line));
}//end for
Though not tested, but you can do something like -
public static void main(String[] args) {
String[] words = {"a", "the", "in", "if", "are", "it", "is"};
List<String> wordList = new ArrayList<>(Arrays.asList(words));
String[] tArray = {"a table is here", "books are sold", "if it is readable"};
List<String> list = new ArrayList<>(Arrays.asList(tArray));
for (int i = 0; i < list.size(); i++) {
String[] tArrays = list.get(i).split(" ");
List<String> line = new ArrayList<>(Arrays.asList(tArrays));
for (String lineElement : line) {
if (wordList.contains(lineElement)) {
line.remove(lineElement);
}
}
list.set(i, String.join(" ", line));
}
for (String string : list) {
System.out.println(string);
}
}
Just to add the java 8 version of doing this kind of filtering:
String[] filtered =
list.stream().map(statement -> Arrays.asList(statement.split(" ")))
.map(listOfWords -> listOfWords.stream()
.filter(word -> !wordList.contains(word))
.collect(Collectors.joining(" "))
)
.toArray(String[]::new);
List<String> filteredList = Arrays.asList(filtered);
You can verify the output using:
filteredList.stream().forEach(System.out::println);
Hope this would be helpful!

I need to randomly remove half of the words in a string in java

Ok so I'm working on this code to blend humanities and STEM. I know very basic java code and so I'm currently trying to stick to String methods. I know using arrays may be easier but I'm not well learned in how to use them. So so far I've made code that counts the words in the string in order to determine how many words to remove (half of them). Next I need to figure out a way to randomly remove half of the words and return a new string, possibly with spaces replacing the removed letters.
Here is my code so far:
public class wordcount
{
public static void main (String[] args)
{
System.out.println("Simple Java Word Count Program");
String str1 = "Look, you want it you devour it and then, then good as it was you realize it wasn’t what you exactly wanted what you wanted exactly was wanting";
String[] wordArray = str1.split("\\s+");
int wordCount = wordArray.length;
System.out.println(str1 + "");
System.out.println("Word count is = " + wordCount);
int wordCount2 = wordCount/2;
}
}
I copied the array to an arrayList to then iterate through the list and delete random elements. I hope this is the type of answer you are looking for.
public static void main(String[] args) {
String str1 = "Look, you want it you devour it and then, then good as it was you realize it wasn’t what you exactly wanted what you wanted exactly was wanting";
String[] wordArray = str1.split("\\s+");
ArrayList<String> wordList = new ArrayList<String>(Arrays.asList(wordArray));
int wordCount = wordList.size();
int halfWordCount = wordCount/2;
int tracker = 0; //counter for iterations in while loop
Random random = new Random();
while(tracker < halfWordCount){
int randomIndex = random.nextInt(wordList.size());
wordList.remove(randomIndex);
tracker++;
}
System.out.println(wordList.toString());
}
import java.util.Arrays;
import java.util.* ;
public class wordcount
{
public ArrayList<Integer> test(Integer[] array)
{
ArrayList<Integer> list = new ArrayList<Integer>();
for(int i=0; i<array.length; i++)
list.add(array[i]);
return list;
}
public ArrayList<String> testS(String[] array)
{
ArrayList<String> list = new ArrayList<String>();
for(int i=0; i<array.length; i++)
list.add(array[i]);
return list;
}
public static void main (String[] args)
{
System.out.println("Removing random words in a Poem Program");
String str1 = "Sample Poem by Noah Eli Gordon: Look, you want it you devour it and then, then good as it was you realize it wasn’t what you exactly wanted what you wanted exactly was wanting";
String[] wordArray = str1.split("\\s+");
int wordCount = wordArray.length;
System.out.println(str1 + "");
//System.out.println("Word count is = " + wordCount);
//System.out.println(wordArray);
//String[] ret = wordArray;
//for(String str : ret)
// System.out.print(str);
int wordCount2 = wordCount/2;
Integer[] myIntArray = new Integer[wordCount];
//for(int i = 0; i<wordCount;i++)
// myIntArray[i] = i;
//for(int str : myIntArray)
//System.out.print(str);
wordcount w = new wordcount();
String[] wordArray2 = new String[wordCount2];
for(int i = 0; i <= wordCount2; i++)
{
int rand = (int)(Math.random()*(myIntArray.length-1));
ArrayList<Integer> list = w.test(myIntArray);
list.remove(rand);
myIntArray = list.toArray(myIntArray);
ArrayList<String> listS = w.testS(wordArray);
listS.remove(rand);
wordArray2 = listS.toArray(wordArray);
}
List<String> list = new ArrayList<String>();
for(String s : wordArray2)
{
if(s != null && s.length() > 0)
{
list.add(s);
}
}
wordArray2 = list.toArray(new String[list.size()]);
//for(int str : myIntArray)
//System.out.println(str);
System.out.println();
String[] ret2 = wordArray2;
for(String str : ret2)
System.out.print(str + " ");
}
}

Sort String "13,5,8,4,2,1,9" in ascending order 1,2,4,5,8,9,13 in Java

How can I sort a string "13,5,8,4,2,1,9" in ascending order, to get 1,2,4,5,8,9,13?
Split the string by commas
Parse each substring into an integer
Sort the resulting collection
If you need the result to be a string (it's not clear), convert each integer back into a string and join them together with commas.
If any of those steps causes you difficulties, please be more specific.
Split it into an array of items with String.split().
Convert to an array of numbers with Integer.valueOf().
Sort the array.
Concatenate it all back into a StringBuilder.
As one liner, using Google Collections (updated with Kevin's suggestion)
Joiner.on(",").join(Ordering.natural().onResultOf(new Function<String, Integer>() {
#Override
public Integer apply(String from) {
return Integer.valueOf(from);
}
}).sortedCopy(Arrays.asList("4,2,7,9,1".split(","))));
Split using String.split()
Transform to Integer using a Function (anyone know if there's a constant for this one somewhere?)
Sort using a TreeSet and natural ordering
Join the parts and transform back to a String using Joiner
(old version)
Joiner.on(',').join(
Sets.newTreeSet(
Iterables.transform(
Arrays.asList("13,5,8,4,2,1,9".split(",")),
new Function<String, Integer>() {
#Override
public Integer apply(String from) {
return Integer.parseInt(from);
}}))));
String s = "13,5,8,4,2,1,9";
String[] arr = s.split(",");
Arrays.sort(arr, new Comparator<String>() {
#Override public int compare(String s1, String s2) {
return Integer.parseInt(s1) - Integer.parseInt(s2);
}
});
s = Arrays.toString(arr).replaceAll("[\\[ \\]]", "");
This solution uses:
java.util.Comparator
java.util.Arrays sort and toString
String split and replaceAll
regular expression
I would tokenize the string using StringTokenizer,
parse the values (using Integer.parseInt),
then sort the results using Arrays.sort.
Lastly, re-create the string.
String str = "13,5,8,4,2,1,9";
StringTokenizer tokens = new StringTokenizer(", ");
ArrayList<Integer> ints = new ArrayList<Integer>();
for(String token: tokens)
ints.add(Integer.parseInt(token));
Collection.sort(ints);
String sortedStr = "";
for(int i = 0; i + 1 < ints.size(); ++i)
sortedStr += ints.get(i) + ", ";
if (ints.size() > 0)
sortedStr += ints.lastElement();
Might have some misspellings, but I think not. Also, add the appropriate imports yourself =)
So you have a string containing a comma-delimited set of integers that you need to sort and then output to a string? Try split-ting the string, parse-ing the integers, sort-ing the resulting array, and then join-ing the results together
Java 8+
If you are using Java 8 you can use streams to sort like so :
String str = "13,5,8,4,2,1,9";
String sortedString =
Arrays.stream(str.split(",")) //split with ','
.map(Integer::valueOf) //convert your strings to ints
.sorted() //sort
.map(String::valueOf) //convert them back to string
.collect(Collectors.joining(","));//1,2,4,5,8,9,13
If you want an sorted array you can also use :
Integer[] sortedInts =
Arrays.stream(str.split(",")) //split with ','
.map(Integer::valueOf) //convert your strings to ints
.sorted() //sort
.toArray(Integer[]::new);//[1, 2, 4, 5, 8, 9, 13]
The idea is the same as Jon Skeet explanation.
An alternative using java.util.Scanner
public class SortString {
public static void main( String [] args ) {
// Read integers using Scanner...
Scanner scanner = new Scanner( "13,5,8,4,2,1,9" ).useDelimiter(",");
// Put them in a Integer list
List<Integer> list = new ArrayList<Integer>();
while( scanner.hasNextInt() ){
list.add( scanner.nextInt() );
}
// And sort it
Collections.sort( list );
System.out.println( list );
}
}
ok you can try this one it work in all case.
package com.java;
import java.util.*;
public class cd
{
public static void main(String s[])
{
Collections col;
List l = sort(s);
System.out.println("\nStrings sorted List ...");
for(int i = 0; i < s.length; i++)
{
System.out.println((String)l.get(i));
}
int ints[] = {
719, 2, -22, 401, 6
};
Integer in[] = new Integer[ints.length];
for(int i = 0; i < in.length; i++)
{
in[i] = new Integer(ints[i]);
}
l = sort(in);
System.out.println("\nIntegers sorted List ...");
for(int i = 0; i < in.length; i++)
{
System.out.println((Integer)l.get(i));
}
}
public static List sort(Object o[])
{
ArrayList al = new ArrayList();
for(int i = 0; i < o.length; i++)
al.add(i, o[i]);
List list = Collections.synchronizedList(al);
Collections.sort(list);
return list;
}
}
This is one way to sorting.
package com.java;
import java.util.ArrayList;
import java.util.Collections;
public class b{
public static void main(String[] args) {
//create an ArrayList object
ArrayList arrayList = new ArrayList();
//Add elements to Arraylist
arrayList.add("9");
arrayList.add("3");
arrayList.add("5");
arrayList.add("2");
arrayList.add("4");
Collections.sort(arrayList);
//display elements of ArrayList
System.out.println("ArrayList elements after sorting in ascending order : ");
for(int i=0; i<arrayList.size(); i++)
System.out.println(arrayList.get(i));
}
}
class SplitStr
{
public static void main(String args[])
{
try
{
String str=args[0]+","+args[1]; //marge two string in one
String sArr[]=str.split(",");
int slen=sArr.length;
int iArr[]=new int[slen];
int temp;
for(int i=0;i<slen;i++)
{
iArr[i]=Integer.parseInt(sArr[i]); //convert String into integer array
}
for(int i=0;i<slen;i++)
{
for(int j=i+1;j<slen;j++)
{
if(iArr[i]>=iArr[j])
{
temp=iArr[i];
iArr[i]=iArr[j];
iArr[j]=temp;
}
}
}
for(int i=0;i<slen;i++)
{
System.out.println(" "+iArr[i]);
}
}
catch(Exception e)
{
System.out.println("input error "+e);
}
}
}
Bash is SO powerful :-)
numbers="1, 2, 9, 4, 7, 5" ; for number in $(echo "$numbers") ; do echo "$number" | tr -d ", "; done | sort | tr "\n" "," ; echo ""

Categories

Resources