Convert lines to different Arrays in Java - java

I have a .txt file with lines (in my situation 2). I need to read lines and convert each to a different Array. Ex:
1 line - A,B,C
2 line - D,E,F,G, etc.
and convert this to:
[A,B,C]
[D,E,F,G]
I'm doing this with String.split(", ")
ArrayList<String> al_1 = new ArrayList<String>();
ArrayList<String> al_2 = new ArrayList<String>();
while(true){
String[] line = rbuff.readLine().split(",");
for(String i : line){
al_1.add(i);
}
if(line == null) break;
}
What's the best way to fill the second?
Thx.

Maybe you must use
ArrayList<ArrayList<String>> al = new ArrayList<ArrayList<String>>();
instead of
ArrayList<String> al_1 = new ArrayList<String>();
ArrayList<String> al_2 = new ArrayList<String>();
and fullfill this list with al.add()

IMO easier to keep a list of lists.
List<List<String>> lineLists = new ArrayList<List<String>>();
while (true) {
List<String> lineList = new ArrayList<String>();
String[] line = rbuff.readLine().split(",");
for (String i : line) {
lineList.add(i);
}
lineLists.add(lineList);
if (line == null) break;
}
(Ignoring that there are any number of ways to split immediately into an array or list w/o the inner loop. Either way, the inner loop should be refactored.)

This solution will allow you to add a new ArrayList to the myArrayList for each row your read of your file:
List<List<String>> myArrayList = new ArrayList<List<String>>();
List<String> myStrings;
while (true) {
myStrings = new ArrayList<String>();
String[] line = rbuff.readLine().split(",");
for (String i : line) {
myStrings.add(i);
}
myArrayList.add(myStrings);
if (line == null)
break;
}
You will have a List with one List inside for each row of your text file.
MyArrayList
|
|_____List('A', 'B', 'C')
|
|_____List('D', 'E', 'F', 'G')
|
|_____(...)

Well that's pretty much what I'd do, but with the mention that if you don't need your lines to inside ArrayList objects, you can use array Strings (String[]). Here's an example:
private static String s1 = "A,B,C",s2="D,E,F";
private static List<String> lines = new ArrayList<String>(){{add(s1);add(s2);}};
public static void main(String[] args) throws Throwable {
Map<Integer,String[]> linesToArraysMap = new HashMap<Integer,String[]>();
for(int i=1;i<=lines.size();i++) {
linesToArraysMap.put(i, lines.get(i-1).split(","));
//if you want to get them as ArrayLists you can do:
//List<String> lineList = Arrays.asList(lines.get(i-1).split(","));
}
for(String[] stringArr:linesToArraysMap.values()) {
System.out.println(Arrays.toString(stringArr));
}
}

Related

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;
}

Array is being returned as empty instead of a list of numbers

Basically, I'm working on a program for my class to find the leading digit of numbers from a text file and sort them. I know I don't have the best coding skills out there since I'm a beginner, but I have an idea on how to do it. Somehow, I've encountered a problem where the array that's suppose to be returned comes out to be empty. This array is returned twice, actually. The first time, to the main method, it returns neatly, but when it's returned to change3(), it returns "[]."
I've tried to change the variables around, and even tried to combine the methods, but nothing works and I just get errors.
import java.io.*;
import java.util.*;
class PG
{
public static void main(String[] args)
{
List<String> Strings = new ArrayList<String>();
Strings = change(); // it works perfectly right here
System.out.println(Strings); // it works perfectly right here
List<Integer> Integers = new ArrayList<Integer>();
Integers = change2();
List<Integer> leads = new ArrayList<Integer>();
leads = change3();
}
public static List<String> change()
{
Scanner in = new Scanner(System.in);
List<String> list_S = new ArrayList<String>();
while (in.hasNextLine())
{
String line = in.nextLine();
line = line.replaceAll(",", "");
int result = Integer.parseInt(line);
List<Integer> list_I = new ArrayList<Integer>();
list_I.add(result);
list_S.add(line);
}
return list_S;
}
public static List<Integer> change2()
{
Scanner in = new Scanner(System.in);
List<Integer> list_I = new ArrayList<Integer>();
while (in.hasNextLine())
{
String line = in.nextLine();
line = line.replaceAll(",", "");
int result = Integer.parseInt(line);
List<String> list_S = new ArrayList<String>();
list_I.add(result);
list_S.add(line);
}
return list_I;
}
public static List<Integer> change3()
{
List<String> list = new ArrayList<String>();
list = change(); // This is supposed to give me a list of numbers(string) so it can help me find the leading digit
System.out.println(list); // checking to see if the list even has numbers in it. It does not. It returns [] as if nothing is in the list.
List<Integer> leads = new ArrayList<Integer>();
for (int i = 0; i < list.size(); i++)
{
// get the leading integer
}
return leads;
}
}
Basically, for right now, I just want it to print the list in the method change3(), so I can continue to work on the program.
Try this code. it should work. if its not working please comment the issue.
Also match this code with your.
There are some changes in change method. I have removed redundant code.
I will suggest to pass the list in all 3 change methods if its same list being used. so you don't have to read it again with the help of scanner.
import java.io.*;
import java.util.*;
class PG
{
public static void main(String[] args)
{
List<String> Strings = new ArrayList<String>();
Strings = change(); // it works perfectly right here
System.out.println(Strings); // it works perfectly right here
List<Integer> Integers = new ArrayList<Integer>();
Integers = change2();
List<Integer> leads = new ArrayList<Integer>();
leads = change3();
}
public static List<String> change()
{
Scanner in = new Scanner(System.in);
List<String> list_S = new ArrayList<String>();
while (in.hasNextLine())
{
String line = in.nextLine();
line = line.replaceAll(",", "");
list_S.add(line);
}
return list_S;
}
public static List<Integer> change2()
{
Scanner in = new Scanner(System.in);
List<Integer> list_I = new ArrayList<Integer>();
while (in.hasNextLine())
{
String line = in.nextLine();
line = line.replaceAll(",", "");
int result = Integer.parseInt(line);
list_I.add(result);
}
return list_I;
}
public static List<Integer> change3()
{
List<String> list = new ArrayList<String>();
list = change(); // This is supposed to give me a list of numbers(string) so it can help me find the leading digit
System.out.println(list); // checking to see if the list even has numbers in it. It does not. It returns [] as if nothing is in the list.
List<Integer> leads = new ArrayList<Integer>();
for (int i = 0; i < list.size(); i++)
{
// get the leading integer
}
return leads;
}
}

Converting Arraylist to an Array [duplicate]

How might I convert an ArrayList<String> object to a String[] array in Java?
List<String> list = ..;
String[] array = list.toArray(new String[0]);
For example:
List<String> list = new ArrayList<String>();
//add some stuff
list.add("android");
list.add("apple");
String[] stringArray = list.toArray(new String[0]);
The toArray() method without passing any argument returns Object[]. So you have to pass an array as an argument, which will be filled with the data from the list, and returned. You can pass an empty array as well, but you can also pass an array with the desired size.
Important update: Originally the code above used new String[list.size()]. However, this blogpost reveals that due to JVM optimizations, using new String[0] is better now.
An alternative in Java 8:
String[] strings = list.stream().toArray(String[]::new);
Java 11+:
String[] strings = list.toArray(String[]::new);
Starting from Java-11, one can use the API Collection.toArray(IntFunction<T[]> generator) to achieve the same as:
List<String> list = List.of("x","y","z");
String[] arrayBeforeJDK11 = list.toArray(new String[0]);
String[] arrayAfterJDK11 = list.toArray(String[]::new); // similar to Stream.toArray
You can use the toArray() method for List:
ArrayList<String> list = new ArrayList<String>();
list.add("apple");
list.add("banana");
String[] array = list.toArray(new String[list.size()]);
Or you can manually add the elements to an array:
ArrayList<String> list = new ArrayList<String>();
list.add("apple");
list.add("banana");
String[] array = new String[list.size()];
for (int i = 0; i < list.size(); i++) {
array[i] = list.get(i);
}
Hope this helps!
ArrayList<String> arrayList = new ArrayList<String>();
Object[] objectList = arrayList.toArray();
String[] stringArray = Arrays.copyOf(objectList,objectList.length,String[].class);
Using copyOf, ArrayList to arrays might be done also.
In Java 8:
String[] strings = list.parallelStream().toArray(String[]::new);
In Java 8, it can be done using
String[] arrayFromList = fromlist.stream().toArray(String[]::new);
If your application is already using Apache Commons lib, you can slightly modify the accepted answer to not create a new empty array each time:
List<String> list = ..;
String[] array = list.toArray(ArrayUtils.EMPTY_STRING_ARRAY);
// or if using static import
String[] array = list.toArray(EMPTY_STRING_ARRAY);
There are a few more preallocated empty arrays of different types in ArrayUtils.
Also we can trick JVM to create en empty array for us this way:
String[] array = list.toArray(ArrayUtils.toArray());
// or if using static import
String[] array = list.toArray(toArray());
But there's really no advantage this way, just a matter of taste, IMO.
You can use Iterator<String> to iterate the elements of the ArrayList<String>:
ArrayList<String> list = new ArrayList<>();
String[] array = new String[list.size()];
int i = 0;
for (Iterator<String> iterator = list.iterator(); iterator.hasNext(); i++) {
array[i] = iterator.next();
}
Now you can retrive elements from String[] using any Loop.
Generics solution to covert any List<Type> to String []:
public static <T> String[] listToArray(List<T> list) {
String [] array = new String[list.size()];
for (int i = 0; i < array.length; i++)
array[i] = list.get(i).toString();
return array;
}
Note You must override toString() method.
class Car {
private String name;
public Car(String name) {
this.name = name;
}
public String toString() {
return name;
}
}
final List<Car> carList = new ArrayList<Car>();
carList.add(new Car("BMW"))
carList.add(new Car("Mercedes"))
carList.add(new Car("Skoda"))
final String[] carArray = listToArray(carList);
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
String [] strArry= list.stream().toArray(size -> new String[size]);
Per comments, I have added a paragraph to explain how the conversion works.
First, List is converted to a String stream. Then it uses Stream.toArray to convert the elements in the stream to an Array. In the last statement above "size -> new String[size]" is actually an IntFunction function that allocates a String array with the size of the String stream. The statement is identical to
IntFunction<String []> allocateFunc = size -> {
return new String[size];
};
String [] strArry= list.stream().toArray(allocateFunc);
List <String> list = ...
String[] array = new String[list.size()];
int i=0;
for(String s: list){
array[i++] = s;
}
in case some extra manipulation of the data is desired, for which the user wants a function, this approach is not perfect (as it requires passing the class of the element as second parameter), but works:
import java.util.ArrayList;
import java.lang.reflect.Array;
public class Test {
public static void main(String[] args) {
ArrayList<Integer> al = new ArrayList<>();
al.add(1);
al.add(2);
Integer[] arr = convert(al, Integer.class);
for (int i=0; i<arr.length; i++)
System.out.println(arr[i]);
}
public static <T> T[] convert(ArrayList<T> al, Class clazz) {
return (T[]) al.toArray((T[])Array.newInstance(clazz, al.size()));
}
}
In Java 11, we can use the Collection.toArray(generator) method. The following code will create a new array of strings:
List<String> list = List.of("one", "two", "three");
String[] array = list.toArray(String[]::new)
from java.base's java.util.Collection.toArray().
You can convert List to String array by using this method:
Object[] stringlist=list.toArray();
The complete example:
ArrayList<String> list=new ArrayList<>();
list.add("Abc");
list.add("xyz");
Object[] stringlist=list.toArray();
for(int i = 0; i < stringlist.length ; i++)
{
Log.wtf("list data:",(String)stringlist[i]);
}
private String[] prepareDeliveryArray(List<DeliveryServiceModel> deliveryServices) {
String[] delivery = new String[deliveryServices.size()];
for (int i = 0; i < deliveryServices.size(); i++) {
delivery[i] = deliveryServices.get(i).getName();
}
return delivery;
}
An alternate one-liner method for primitive types, such as double, int, etc.:
List<Double> coordList = List.of(3.141, 2.71);
double[] doubleArray = coordList.mapToDouble(Double::doubleValue).toArray();
List<Integer> coordList = List.of(11, 99);
int[] intArray = coordList.mapToInt(Integer::intValue).toArray();
and so on...

Split ArrayList of sentences into words, store the words into new ArrayList

I've done some research, and maybe I'm just not asking the right questions.
I have an ArrayList of sentences. I want to split the sentences and store individual words into a new ArrayList to use later. I've included code.
This is my first post. If something is incorrect, I apologize in advance.
FYI, rawLinesTest is my ArrayList of sentences.
public List<String> getRawWords()
{
String[] tokens = rawLinesTest.toArray(new String[0]);
for(String s : tokens)
{
tokens = s.split("[^\\w]+");
rawWords = Arrays.asList(tokens);
}
return rawWords;
}
Solution:
public ArrayList<String> getRawWords(String s)
{
String[] s2 = s.split(" ");
ArrayList<String> words = new ArrayList<String>();
for(int x =0; x< s2.length-1;x++)
{
words.add(s2[x]);
}
return words;
}
To use later just assign a arraylist to the returned list....
String sentence = "A Test Sentence";
ArrayList<String> q = new ArrayList<String>();
q = getRawWords(sentence);

parse array and extract string of same length

my first question.
lets say i have arraylist of strings in java
ArrayList<string> s= new ArrayList<string>;
and it contains sorted list by size.
s.add("ab");
s.add("abc");
s.add("aab");
s.add("baab");
s.add("abcd");
what i want to do is, iterate the list and pick group of elements which has same length and put into seprate array of arrays.
Group 1 ab
Group 2 abc,aab and so on...
i am doing this in java please help
Since they're sorted by size already it's easy. Here's one way that works:
ArrayList<ArrayList<String>> listofLists = new ArrayList<ArrayList<String>>();
int length = -1;
for(String str : s) { // where s is your sorted ArrayList of Strings
if(str.length() > length) {
listofLists.add(new ArrayList<String>());
length = str.length();
}
listofLists.get(listofLists.size()-1).add(str);
}
At the end, listofLists will be an ArrayList of ArrayLists containing groups of Strings of the same length. Again, this depends on s (your ArrayList<String>) being sorted by size. Also, String must be capitalized there.
You can use this code "it works as you need"
import java.util.ArrayList;
public class Test{
public static void main(String[] args){
ArrayList<String> s = new ArrayList<String>();
s.add("ab");
s.add("abc");
s.add("aab");
s.add("baab");
s.add("abcd");
String[] group1 = new String[s.size()];
String[] group2 = new String[s.size()];
String[] group3 = new String[s.size()];
for(int i = 0 ; i < s.size() ; i++){
if(s.get(i).length() == 2)
group1[i] = s.get(i);
else if(s.get(i).length() == 3)
group2[i] = s.get(i);
else
group3[i] = s.get(i);
}
for(String ss : group1){
if(ss == null)
break;
System.out.println(ss);
}
System.out.println();
for(String ss : group2){
if(ss == null)
continue;
System.out.println(ss);
}
System.out.println();
for(String ss : group3){
if(ss == null)
continue;
System.out.println(ss);
}
}
}
I hope it useful for you.

Categories

Resources