1

I am trying to do the following....

I have a list of string in the following mode:

John,Peter,Carl
Rose,Joanne,Natalie

At the moment I am reading line by line and outputting a stream...

Like this:

 Files.lines(myfile).toURI()))

This returns a stream.

I know I can collect them into a list but I am wondering if inside this stream I can split and do some more logic?

I try to split each line and filter in case any of the three expected fields is empty, is it possible?

At the moment I have it in the "old way" like this:

List<TripleNames> validValues = new ArrayList();
for(String value:values) { //values represent each line comma separated
   final String[] names = line.split(",");
   if (StringUtils.isNotBlank(names[0]) && StringUtils.isNotBlank(names[1]).... {
    validValues.add(new TripleNames(names[0], names[1], names[2]);
   } 
}

Any ideas?

2 Answers 2

2

You might be looking for mapping before collecting to a List as :

List<TripleNames> validValues = values.stream()
        .map(line -> line.split(","))
        .filter(names -> StringUtils.isNotBlank(names[0]) && StringUtils.isNotBlank(names[1]))
        .map(names -> new TripleNames(names[0], names[1], names[2]))
        .collect(Collectors.toList());
1
  • You also need to check names[2] for blankness. You can use StringUtils#isNoneBlank to check all at once.
    – Kartik
    Apr 2, 2019 at 3:42
0

If you want a simple way to check all splitted items, you can use:

Arrays.stream(names).allMatch(StringUtils::isNotBlank)

Instead of checking each each item separately in a condition.

Here is the full example:

List<String> validValues = values.stream()
    .map(line -> line.split(","))
    .filter(names -> Arrays.stream(names).allMatch(StringUtils::isNotBlank))
    .map(names -> new TripleNames(names[0], names[1], names[2]))
    .collect(Collectors.toList());

You also can use .map(String::trim) before .allMatch() to to cut of white spaces at the beginning and the end of all names, if that helps.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.