3

Try to studying Stream API. So, I have a list of strings like this:

118.111.97.113
119.122.122.122
122.122.122.97
122.122.122.99
122.122.122.100

I need to split it by '.' and separate numbers put as separate value to new collection. Like this:

118
111
97
113
119
...

I know about flatMap method, that can assume one value and return several, but how use it correctly, have no one idea. Can you help me or give some ideas?

Thanks!

2
  • 2
    think of flatMap as squeezing a fruit with seeds, you get one fruit as input and lots of seeds as output Commented Jul 16, 2018 at 14:16
  • 1
    @Eugene Ooooh!!! Delicious!! Commented Jul 16, 2018 at 14:17

2 Answers 2

5

You may do

List<String> initial;
List<String> all = initial.stream().flatMap(str -> Arrays.stream(str.split("\\.")))
                                   .collect(Collectors.toList());
Sign up to request clarification or add additional context in comments.

5 Comments

@Eugene "\\." is a single character delimiter for which String.split will not create a Pattern at all.
@Holger isn't that an internal detail? :)
@Eugene Not different to assuming that creating a Pattern each time is expensive or that there is no Pattern cache behind String.split. Sometimes, when you have to make a choice between two equivalent variants, you have to consider what is reasonable to expect from implementations and what the common implementation(s) actually do…
@Eugene I did some quick test, list ok 100k elem, 50iterations, and it's not quicker at all to build the pattern before, even sometimes it's slower
@azro then this is a problem of some warm-up I guess, not an indication of which is slower/faster
5

Something alone the lines of:

Pattern p = Pattern.compile("\\.");
yourStreamOfStrings.flatMap(p::splitAsStream)
            .collect(Collectors.toList());

Comments

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.