I have a list of string arrays that I am reading from a csv file that I want to filter using Java. I would like to retrieve the whole String array that contains a particular value.
List<String[]> csvData = readAllData("src/test/resources/data.csv", ';');
The output after printing:
[24, Desnoyers Claude, 1030311841077]
[25, Doiron Fletcher, 1680375680748]
[63, Mainville Agathe, 2680408184680]
[363, Pinette Searlas, 1940914809627]
For instance, I would like to retrieve the whole array that contains a particular name, like Doiron Fletcher, regardless of its index. I know that I can use stream in Java 8, but I am fairly new to Java and don't really know how to do it for lists of string arrays. Any ideas on how I can do this?
CodePudding user response:
You can take knowledge of that "name" is the second element of your array.
Before Java 17:
List<String[]> filteredData = csvData.stream()
.filter(item -> "Doiron Fletcher".equals(item[1]))
.collect(Collectors.toList()));
Java 17 :
List<String[]> filteredData = csvData.stream()
.filter(item -> "Doiron Fletcher".equals(item[1]))
.toList());
Or if you need only one (e.g. the first) row:
String[] foundRow = csvData.stream()
.filter(item -> "Doiron Fletcher".equals(item[1]))
.findFirst().orElse(null);