1

This is a follow up question of How to map strings to URIs?

I have a String of URIs delimited with some white spaces.

http://...[sp]http://...[sp]http://...

I'm trying to split it and, finally, collect them to a List.

I, so far, wrote following codes.

final List<URI> uris = Stream.of(string.split("\\s"))
    .distinct()
    .filter(s -> s.isEmpty())
    .map(s -> {
        try {
            return new URI(s);
        } catch (final URISyntaxException urise) {
            return null;
        }
    })
    .filter(uri -> uri != null)
    .collect(Collectors.toList());

My question is,

  1. Is null creation by URI constructor and following filtering is inevitable?
  2. Is there any more effective way to do this?
Community
  • 1
  • 1
Jin Kwon
  • 20,295
  • 14
  • 115
  • 184

1 Answers1

1

This should be enough:

List<URI> uris = Stream.of(string.split("\\s+")).map(URI::create).collect(
    Collectors.toList());

It will throw an exception if any invalid input is encountered, but I'm of the opinion that errors should be exposed, not quietly suppressed.

VGR
  • 40,506
  • 4
  • 48
  • 63