0

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.

1
  • why not using match() or contains()? Commented May 12, 2020 at 20:47

1 Answer 1

1

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")

Sign up to request clarification or add additional context in comments.

6 Comments

might also be worth mentioning the argument to filter should be a function given the OP is calling it as .filter(r[2].startsWith("f")). unless it's just a typo when posting his question...
I made this change .map(row -> row.split(",")) to this .map(row -> row.split(", ")). Still can't filter with .filter(r[0].startsWith("f")). Netbeans says: can not find symbol.
Use .filter(r -> r[2].startsWith("f")) if you've made that change
use split(" *, *) to skip any spaces
@Lasse, if this answer works for you, consider accepting it.
|

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.