How to store data in a string array using java collection

how to store string in array in java
how to retrieve values from string array in java
dynamic string array in java
how to store values in array in java
how to store multiple values in string in java
how to declare string array in java without size
how to get first element of string array in java
string array input in java

I have stored data in a List<String[]> and need to store those data into an another String array using a loop. I have created a String array (value) and stored data in there but the issue is first element is getting replaced by second inside the loop and it will show only the last element at the end of the loop.

CSVReader reader = new CSVReader(new FileReader(csvfile));
List<String[]> data = reader.readAll();
String[] values = new String[5];
for (int i = 1; i < 5; i++) {
    values = data.get(i);
    System.out.println(values[1]); // data is getting replaced here
}
System.out.println(values[1]); // this will show only the last stored value
  1. Lists are 0 indexed so unless you intentionally want to skip the first element then don't start the loop iteration at 1 rather at 0.
  2. Yes, when performing the last println after the loop only data related to the last String[] is shown because at each iteration you're updating values i.e. values = data.get(i); to store the current String[] hence the aforementioned outcome.
  3. You probably want a String[][] as opposed to String[] because each String[] represents a line of the file.

Thus, assuming you only want to get the first five lines from data you can do it as:

String[][] lines = data.subList(0, 5).toArray(String[][]::new);

or for all the lines read:

String[][] lines = reader.readAll().toArray(String[][]::new);

and you can test it with:

System.out.println(Arrays.deepToString(lines));

Java String Array Examples, Here are some examples on how to use String Array in Java. Here is an example of declaring a String Array with size 5 and assigning values to This method acts as bridge between array-based and collection-based APIs, in combination with This is very useful for storing more complex information. Apart from classes, Java provides basic data types that can store a collection of homogeneous data. One such data type is the Java array data type. Arrays are used to store collections of data of the same type. The following example demonstrates syntax of a basic integer type array: int num [] = new int [10];

    // generating data
    List<String[]> data =
            Stream.iterate(0,  n -> n + 1)
                    .limit(10)
                    .map(i -> new String[]{"a" + i, "b" + i, "c" + i, "d" + i, "e" + i, "f" + i})
                    .collect(Collectors.toList());

    String[][] values = new String[data.size()][];

    // copy the data
    for (int i = 0; i < data.size(); i++)
    {
        values[i] = data.get(i).clone();
    }

    //print the result
    Arrays.stream(values).map(Arrays::toString).forEach(System.out::println);

How to store elements in a list of String array in a java array? [closed], You would not be able to easily convert List<String[]> to String[] since they have different dimensions. It is like when you render 3d scene on a  The string array can also be declared as String strArray[], but the previously mentioned methods are favoured and recommended. Note that the value of strArray1 is null, while the value of strArray2 is [null, null]. Now let us move ahead and checkout how to initialize a string array, Initializing A String Array In Java. A string array can be

Replace :

for (int i = 1; i < 5; i++) {
values = data.get(i);
System.out.println(values[1]); // data is getting replaced here}

With:

for (int i = 0; i < 5; i++) {
values = data.get(i);
System.out.println(values[1]); // data is getting replaced here}

Java Collections - Tutorial, The data stored in the collection is encapsulated and the access to the data is only Collections use internally arrays for there storage but hide the is parameterized with <String> to indicate to the Java compiler that only  To sort a String array in Java, you need to compare each element of the array to all the remaining elements, if the result is greater than 0, swap them. One solution to do so you need to use two loops (nested) where the inner loop starts with i+1 (where i is the variable of outer loop) to avoid repetitions in comparison.

I think you have a little error inside the for loop. Try this:

CSVReader reader = new CSVReader(new FileReader(csvfile));
List<String[]> data = reader.readAll();
String[] values = new String[5];
for (int i = 1; i < 5; i++) {
    values[i] = data.get(i);
    System.out.println(values[1]); // data is getting replaced here
}
System.out.println(values[1]); // this will show only the last stored value

I think you are missing the "[i]" at the first line inside the for loop.

Java String Array | String Array in Java with Examples, String Array is used to store a fixed number of Strings. You must be aware of Java Arrays, it is an object that contains elements of a similar data type. To create a collection of elements that are unique in nature, Set proves  Java String Array Examples. Oct 14, 2015 Array, Core Java, Examples, Snippet, String comments A Java String Array is an object that holds a fixed number of String values. Arrays in general is a very useful and important data structure that can help solve many types of problems.

Your data variable contains a list of String[] (string arrays). Your for loop is attempting to store them in values which is a single String[].

Depending on what you are trying to do, you can do as the comments suggest and make a 2D String array. However, the fact that you want to remove them from a perfectly good list of String[]'s leads me to believe you probably want them in one big String[].

Below is an example of how to put the first N (in this case 5) words you parse from the csv into the values variable. However, we would be able to give you better guidance if you provided what the ultimate use case of your code snippet is.

    // initialize test data
    List<String[]> data = new ArrayList<String[]>();
    String[] a = {"a1", "a2"};
    String[] b = {"b1", "b2"};
    String[] c = {"c1", "c2"};
    data.add(a);
    data.add(b);
    data.add(c);

    // big N is how many words you want
    int N = 5;
    // little n tracks how many words have been collected
    int n = 0;
    String[] values = new String[N];
    // loop through csv collect
    for (int i = 0; i < data.size(); i++){
        String[] cur = data.get(i);
        // loop through the strings in each list entry
        for (int j = 0; j < cur.length; j++){
            // store value and increment counter
            values[n] = cur[j];
            n++;
            // stop if maximum words have been reached
            if (n >= N)
                break;
        }
        // stop if maximum words have been reached
        if (n >= N)
                break;
    }

    for (int i = 0; i < values.length; i++)
        System.out.println(values[i]);

Java String array examples (with Java 5 for loop syntax , How to create a String array in Java · Tip Your Barista (author)?. help keep this website running. The Java language supports arrays to store several objects. An array is initialized with an predefined size during instantiation. To support more flexible data structures the core Java library provides the collection framework. A collection is a data structure which contains and processes a set of data.

Convert an ArrayList of String to a String array in Java , Given an ArrayList of String, the task is to convert the ArrayList to String array in java. Find the size of ArrayList using size() method, and Create a String Array of this size. Start learning Data Sructures & Algorithms with the help of the most trusted DSA Self Paced course, and that too at the most Java-Collections. The syntax of creating an array in Java using new keyword −. type [] reference = new type [10]; Where, type is the data type of the elements of the array. reference is the reference that holds the array. And, if you want to populate the array by assigning values to all the elements one by one using the index −.

Arrays and references | Think Java, In this chapter, we'll learn how to store multiple values of the same type using a You can make an array of int s, double s, String s, or any other type, but all the  Java array size: This will give you the number of elements in the Array List. Just like arrays, here too the first element starts with index 0. Just like arrays, here too the first element starts with index 0.

Day 5 -- Arrays, Conditionals, and Loops, Arrays. Arrays in Java, as in other languages, are a way to store collections of items That line creates a new array of Strings with 10 slots (sometimes called elements). You can then assign actual values or objects to the slots in that array. Java Arrays. Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value. To declare an array, define the variable type with square brackets:

Comments
  • The index of the first element in an array is zero. Try for ( int i = 0; ...
  • You probably need to declare values as String[][] (A 2D array)
  • because of this values = data.get(i); same reference will be replaced with values always, and better explain what do you need also
  • He wants make a copy using a loop.
  • @Michel_T. well, they are only using a for loop because they might not know an "easier" way to do it as shown above.
  • He wrote need to store those data into an another String array using a loop But I'm completely with you on this - your method is better that using a loop.
  • 1) you might want to get rid of the testing data you've set up. it would make the code look cleaner and only focus on the code given by the OP. 2) Although, it's a matter of choice I think you may agree with me that System.out.println(Arrays.deepToString(values)); would be easier to print the values of the 2D array. 3) may be a little explanation about your code would help the OP understand what's going on. otherwise, +1 for showing a for loop approach.
  • Yes, Arrays.deepToString it's a good way to make a string. I didn't know about it. Thank you for this knowledge :). The only think better in showing 2D array in my way is that you're seeing the array as a 2D array - every row in its own line whereas deepToString shows all the subarrays in one string which is not so demonstrative in debug.