-1

I cant use loops like for/while. forEach is okay.

I have a list like this:

List<String> listStrings = new ArrayList<String>(); 
listStrings.add("12 14 15"); 
listStrings.add("15 13 17"); 
listStrings.add("14 15 13"); 

How do I split each String with .split() in this list at the " " without using for/while loops?

How the new List newList is supposed to look like:

List<String> newList {"12", "14, "15", "15", ...}

("Why cant you use loops like for/while"-> its for a task and I have to practise using streams.)

Thank´s in advance.

okaycoolG
  • 3
  • 2
  • 2
    If we do it for you, we will practice, but you won't. Why not read the documentation, and try something? That's how one practices. – JB Nizet Jan 05 '20 at 12:42
  • I already did. All I found was about one splitting one string and saving his split parts in an array. That doesnt help me. – okaycoolG Jan 05 '20 at 12:44
  • @okaycoolG , use `flatmap` to flatten each elements in list and then split the list on the basis of `" "` – Vishwa Ratna Jan 05 '20 at 12:45
  • If you know how to loop through strings, and you also know how to split one string, then you can split multiple strings: you loop through the strings, and for each one, you split it. You should at least try doing that. – JB Nizet Jan 05 '20 at 12:46
  • @JBNizet like the other answer shows, its not necessary to use a loop. – okaycoolG Jan 05 '20 at 12:53
  • 1
    Of course it's not the ideal solution. But you **asked** for a solution using forEach. Read your question. And it's easier to start with simpler things first when practicing. – JB Nizet Jan 05 '20 at 12:54
  • If you read my question carefully it says forEach is "okay". Im learning functional java programming so using no loop at all and just collecting in a new list is perfect. – okaycoolG Jan 05 '20 at 12:57
  • And its title says "How do I use .split() on each one (with forEach)?". I know how to use streams. I know very well about flatMap. Whether you should or not use forEach doesn't matter. What you should do though, is read the javadoc, try things before asking, and show your efforts in the question. – JB Nizet Jan 05 '20 at 13:01

1 Answers1

0

You don't need any loop to create a list, just collect the stream

Stream.of("12 14 15", "15 13 17", "14 15 13")  // Stream<String>
  .map(s -> s.split(" "))  // Stream<String[]>
  .flatMap(Stream::of) // Stream<String>
  .collect(Collectors.toList());  // List<String>

If you must start with a list, then replace first line with listStrings.stream()

See example here

Otherwise, you just add within a forEach

Stream.of("12 14 15", "15 13 17", "14 15 13").
  .map(s -> s.split(" "))  // Stream<String[]>
  .flatMap(Stream::of) // Stream<String>
  .forEach(s -> newList.add(s));
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245