Cael
Cael

Reputation: 556

Converting List<List<String>> to array

I have elements that is declared in a list variable such as:

List<List<String>> textList = new ArrayList<>();

The elements are added such as:

textList.add(Arrays.asList(p)); //adding elements

The only way I could output the elements inside the variable is by using:

 for(List<String>  s: textList){
      System.out.println(s); }

which output elements like this:

[He is a boy.]
[He likes apple.]
[She is a girl.]

Now, I would like to store them in an array so that the elements will look like this when outputted.

[He is a boy., He likes apple., She is a girl.]

I've tried

String[] textArr = new String[textList.size()];
textArr = textList.toArray(textArr);

for(String s : textArr){
    System.out.println(s);}

but I got an error about:

Exception in thread "main" java.lang.ArrayStoreException
at java.lang.System.arraycopy(Native Method)
at java.util.Arrays.copyOf(Arrays.java:3213)
at java.util.ArrayList.toArray(ArrayList.java:407)

So, how do I convert the elements inside a list into array using the proper way. Thanks!

Upvotes: 0

Views: 2456

Answers (4)

cks
cks

Reputation: 1

Adding another approach using Stream.flatMap() but making use of method references.

List<List<String>> textList = new ArrayList<>();

textList.add(List.of("He is a boy."));
textList.add(List.of("He likes apple."));
textList.add(List.of("She is a girl."));

String[] textArr = textList.stream() //creates a Stream<List<String>>
   .flatMap(Collection::stream)     //maps each List to a Stream<String> and then flattens all individual Streams to a single one
   .toArray(String[]::new);         //to array

System.out.println(Arrays.toString(textArr)); //"[He is a boy., He likes apple., She is a girl.]"

Upvotes: 0

Kaostias
Kaostias

Reputation: 321

You can use Iterator in order to go over every element of the list, instance of the for each statement (I personally like the iterators more). The code you could use would be something like

         //Your list
    List<List<String>> textList = new ArrayList<>();

    //The iterators
    Iterator<List<String>> itList = textList.iterator();
    Iterator<String> itString;

    //The string to store the phrases
    String s[] = new String[textList.size()];

    int i =0;

    //First loop, this seeks on every list of lists
    while(itList.hasNext()){
        //Getting the iterator of strings
        itString = itList.next().iterator();

        s[i] = "";
        //2nd loop, it seeks on every List of string
        while(itString.hasNext()){
           s[i] = s[i].concat(itString.next());
        }
        s[i] = s[i].concat(".");
        i++;
    }

Upvotes: 0

piegames
piegames

Reputation: 1121

Using streams and flatMap, you can do this:

List<List<String>> list = ...;
String[] strings = list.stream().flatMap(l -> l.stream()).collect(Collectors.toList()).toArray(new String[0]);

This is equivalent to using a loop (You can use two nested for loops as suggested in the comments instead by replacing the addAll, but why?):

List<List<String>> list = ...;
List<String> stringList = new ArrayList<>();
for (List<String> l : list)
  stringList.addAll(l);
String[] strings = list.toArray(new String[stringList.size()]);

Upvotes: 0

GhostCat
GhostCat

Reputation: 140457

Your problem is that you are not storing Strings in your list textList.

textList.add(Arrays.asList(p));

As the type says, you have a List of List of String here.

So you can't take the elements of that list and assume they are Strings. Because they aren't! The error message tells you that: toArray() wants strings it can put into that array of strings, but you give it a List of List of String!

But thing is: what you are describing here doesn't make sense in the first place. Printing strings shouldn't care if strings are in an array or a List.

What I mean is: when you manually iterate a List or an array to print its content, then it absolutely doesn't matter if you iterate a List or an array. The code is even the same:

for (String someString : someCollection) { 
  System.out.println(someString);
}

someCollection can be both: array or List!

In other words: the idea to turn data that is nicely stored within Lists into arrays for printing simply doesn't make any sense. To the contrary: you are probably calling toString() on your List object, and the result of that ... isn't 100% what you want. But I guarantee you: calling toString() on some array will result in something you totally will not want.

Long story short: forget about converting to Arrays; simply iterate your List of List of Strings and use a StringBuilder to collect the content of that collection the way you want to see it (you simply append those [ ] chars to that builder in those places you want them to see).

(if you insist on that conversion to array, the key point there to understand is that only a List of String can be turned into an array of string. So a List of List ... doesnt work that easy).

Upvotes: 3

Related Questions