Lasse
Lasse

Reputation: 141

Filter java stream by array index

I am having a file with rows like this:

Adult literacy rate, population 15+ years, female (%),United Republic of Tanzania,2015,76.08978
Adult literacy rate, population 15+ years, female (%),Zimbabwe,2015,85.28513
Adult literacy rate, population 15+ years, male (%),Honduras,2014,87.39595
Adult literacy rate, population 15+ years, male (%),Honduras,2015,88.32135

If I do this:

try {
            Stream<String> file = Files.lines(Paths.get("file.csv"));
                file
                .filter(r -> r.startsWith("f",43))
                .forEach(r -> System.out.println(r));
                file.close();
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
    }

I get females. Why this does not work?

        .map(row -> row.split(","))
        .filter(r[2].startsWith("f"))

I can print r[2] like this

    .forEach(r -> System.out.println(r[2]));

So that r[2] at least exists.

Upvotes: 0

Views: 87

Answers (1)

user
user

Reputation: 7604

You have spaces after your commas, so the split method will return strings that start with commas. Therefore, you need to use r.split(",")[2].charAt(1) == 'f' or r.split[2].startsWith(" f") to account for that space.

file
  .filter(r -> r.split(",").startsWith(" f")) OR .filter(r -> r.split[2].charAt(1) == 'f')
  .forEach(r -> System.out.println(r));

Also, as Ousmane D. pointed out, you shouldn't have .filter(r[2].startsWith("f"), it should be .filter(r -> r[2].startsWith(" f"), but that's probably just a typo

User8641 has also suggested using the regex " *, *" with the split method to remove all spaces before and after commas, so that you can keep using your original startsWith("f")

Upvotes: 1

Related Questions