Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filter List of String arrays based on value in String array

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can take knowledge of that "name" is the second element of your array:

List<String[]> filteredData = csvData.stream()
        .filter(item -> "Doiron Fletcher".equals(item[1]))
        .collect(Collectors.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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading