I have a list that is holding multiple numbers in the same index, with all but the last number separated by a comma. I'd like to get all these numbers and transfer them to an array, but I want all individual numbers to be in different indexes in this new array. How can I achieve that? I was unable to find a problem similar to mine and have been struggling with it for a while.
I've considered that my way of collecting the data from the data.csv
file could be considered bad and I need something completely different.
My Main class:
public static void main(String[] args) throws FileNotFoundException {
String file = "data.csv";
String line;
List<String> list = new ArrayList<String>();
int i = 0;
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
while((line = br.readLine()) != null){
//System.out.println(line);
list.add(i, line);
i++;
}
} catch (Exception e){
System.out.println(e);
}
Data.csv file:
20,16,23,20,2,17,9,16,0,6
20,18,16,4,10,9,4,10,16,16
3,6,19,14,14,0,5,22,4,15
19,22,6,18,9,12,15,9,25,14
20,0,1,20,6,19,20,16,15,6
13,1,6,1,4,22,3,11,1,12
10,9,20,7,21,22,3,14,1,8
25,19,21,14,15,16,25,17,6,14
0,20,10,1,3,24,24,5,10,24
2,13,0,9,18,5,21,2,24,21
17,4,16,6,22,14,15,5,10,20
6,15,10,8,10,10,16,22,15,22
2,1,3,25,15,19,0,13,7,17
24,20,6,7,3,3,12,22,23,17
12,10,10,14,2,18,21,5,21,3
13,9,20,11,8,3,23,5,5,3
4,18,4,9,1,2,24,21,23,3
3,3,2,19,6,19,1,10,5,4
13,0,12,19,24,7,10,18,18,1
0,7,10,2,22,20,21,4,3,11
Expected result:
Data[0] = 20
Data[1] = 16
Data[2] = 23
Data[10] = 20
Data[11] = 18
The line that you're reading still has lots of numbers that you want to add to your list individually. Use split
to split them into an array of values. Convert that array to a List with Arrays.asList
, them add them all to your target list with the addAll
method.
String line;
List<String> list = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
while((line = br.readLine()) != null){
list.addAll(Arrays.asList(line.split(",")));
}
} catch (Exception e){
e.printStackTrace();
}
You can always convert the List
to an array with
String[] values = list.toArray(String[]::new);
If you'd like to use Java Streams, create a Path
, get the lines, and for each line, split
into an array of values, convert to a List
, use flatMap
to flatten the Lists
to a stream of values, then collect to a List
.
List<String> list = null;
try {
list = Files.lines(Path.of(file))
.map(line -> line.split(","))
.map(Arrays::asList)
.flatMap(List::stream)
.collect(Collectors.toList()); // or .toList(); with Java 16+
} catch (Exception e){
e.printStackTrace();
}
Or you can convert the Stream
directly to an array, replacing the call to collect
or toList
with toArray
:
String[] values = Files.lines(Path.of(file))
.map(line -> line.split(","))
.map(Arrays::asList)
.flatMap(List::stream)
.toArray(String[]::new);