Print a string from ArrayList of String[]? - java

I have an ArrayList full of strings arrays that I built like this:
String[] words = new String[tokens.length];
I have three arrays like above in my ArrayList:
surroundingWords.add(words);
surroundingWords.add(words1);
surroundingWords.add(words2);
etc
Now if I want to print out the elements in the String arrays within surroundingWords... I can't.
The closest I can get to displaying the contents of the String[] arrays is their addresses:
[Ljava.lang.String;#1888759
[Ljava.lang.String;#6e1408
[Ljava.lang.String;#e53108
I've tried a lot of different versions of what seems to be the same thing, the last try was:
for (int i = 0; i < surroudingWords.size(); i++) {
String[] strings = surroundingWords.get(i);
for (int j = 0; j < strings.length; j++) {
System.out.print(strings[j] + " ");
}
System.out.println();
}
I can't get past this because of incompatible types:
found : java.lang.Object
required: java.lang.String[]
String[] strings = surroundingWords.get(i);
^
Help!
I've already tried the solutions here: Print and access List

Try something like this
public class Snippet {
public static void main(String[] args) {
List<String[]> lst = new ArrayList<String[]>();
lst.add(new String[] {"a", "b", "c"});
lst.add(new String[] {"1", "2", "3"});
lst.add(new String[] {"#", "#", "!"});
for (String[] arr : lst) {
System.out.println(Arrays.toString(arr));
}
}
}

Cast the Object into a String[]:
String[] strings = (String[]) surroundingWords.get(i);
or use a parameterized ArrayList:
ArrayList<String[]> surroundingWords = new ArrayList<String[]>();
Then you won't have to cast the return value from get().

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

How to split strings of list into string array

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

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...

How to combine arrays into one array in while loop in Java

I have a stream of strings from a csv file. These strings are converted to arrays and must be put in an Object's setter and the Object in a hashMap as a value. How do i concatenate all comming Arrays into one and only then use the Set method? Is there any better solution than concatenating the arrays before the set method?
Here is my code:
HashMap<Integer, Publication> innerMap = new HashMap<>();
try {
CsvReader csv = new CsvReader(filename);
csv.readHeaders();
while (csv.readRecord()) {
int id = Integer.parseInt(csv.get("ID"));
Publication pub = new Publication();
String names = csv.get("Names");
String[] namesArr = names.split(",");
if (!innerMap.containsKey(id)) {
innerMap.put(id, new Publication());
}
String[] merged = ????
pub.setNames(merged);
innerMap.put(au.getIdx(), pub);
}
csv.close();
} catch (IOException e) {
System.out.println("Exception : " + e);
}
Store them in a List first:
List<String[]> list = new ArrayList<>;
...
list.add(namesArr);
Then, once you've finished reading:
int size = 0;
for (String[] arr : list) {
size += arr.length;
}
List<String> all = new ArrayList<>(size);
for (String[] arr : list) {
all.addAll(Arrays.asList(arr));
}
The first loop helps to allocate the necessary memory to hold all of the data (otherwise there may be lots of reallocations and array copying in the ArrayList internally while you are adding elements to it in the second loop).
this has already been answered using Apache commons - How can I concatenate two arrays in Java?
Here's a pure java 8 way
String[] arr1 = { "a", "b", "c", "d" };
String[] arr2 = { "e", "f", "g" };
Stream<String> stream1 = Stream.of(arr1);
Stream<String> stream2 = Stream.of(arr2);
String[] arr = Stream.concat(stream1, stream2).toArray(String[]::new);
It looks like that if the map key exists, you want to extract the values, append additional values and then put it back in.
I would use a getter, then run this concat function which returns a new array. Since an Array is capped by its size, you cant grow it unless you make a new array and copy everything over.
to concat 2 string arrays where A comes first:
String[] concat( String[] a, String[] b){
String[] out = new String[a.length + b.length]();
int i = 0;
for (int j = 0; j < a.length; j++){
out[i] = a[j]
i++;
}
for (int j = 0; j < b.length; j++){
out[i] = b[j];
i++;
}
return out;
}

adding String array into ArrayList

I want to append a and b string arrays to arrayList. But "1.0" have to be "1" using with split. Split method returns String[] so arrayList add method does not work like this.
Can you suggest any other way to doing this ?
String[] a = {"1.0", "2", "3"};
String[] b = {"2.3", "1.0","1"};
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add(a[0].split("."));
arrayList.add(a[0].split("\\.")[0]);
Should be as below
arrayList.add(a[0].split("\\.")[0]);
Split method returns an array. You have to access to his position to get the number.
arrayList.add(a[0].split("\\.")[0]);
You can also use substring method:
arrayList.add(a[0].substring(0, 1));
Access first element of that array like this :
for (int i = 0; i < a.length; i++) {
if (a[i].contains("."))
arrayList.add(a[i].split("\\.")[0]);
else
arrayList.add(a[i]);
}
Why split it?. Just use a replaceAll(), it will be more efficient as it won't create an array of Strings.
public static void main(String[] args) {
String[] a = { "1.7", "2", "3" };
List<String> arrayList = new ArrayList<String>();
for (int i = 0; i < a.length; i++) {
arrayList.add(a[i].replaceFirst("\\..*", "")); // escape the . (match it as a literal), then followed by anything any number of times.
}
System.out.println(arrayList);
}
O/P :
[1, 2, 3]
If you use Java 8,
String[] a = {"1.0", "2", "3"};
List<String> list = Arrays.stream(a).map(s -> s.split("\\.")[0]).collect(Collectors.toList());
// OR
List<String> list2 = Arrays.stream(a).map(s -> {
int dotIndex = s.indexOf(".");
return dotIndex < 0 ? s : s.substring(0, dotIndex);
}).collect(Collectors.toList());
This is working properly for me: arrayList.add(a[0].split("\\.")[0]);

Categories

Resources