0

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?

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Note: toList() has been around since Java 16.
Strictly speaking yes. But it is a somewhat 'minor' Java revision and most developers start working either with Java 8 (or earlier) / 11 or with 17. I think memorizing too many versions would be a bit overcomplication for beginners.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.