0

I have a small problem, namely I want to get Integer from a String via lambda expression. I wrote small code but i get only single chars.

Example:

String = "He11o W00rld"

I get [1, 1, 0, 0] but I want [11, 00]. Is there any solution for this?

My code:

Function<String, List<Integer>> collectInts = f -> { 
    return f.chars()
            .filter( s -> (s > 47 && s < 58))
            .map(r -> r - 48)
            .boxed()
            .collect(Collectors.toList());};
3
  • Any particular reason you need to do it by lambda expression? Commented Apr 8, 2016 at 17:47
  • Yes i must do this for study exercises... Commented Apr 8, 2016 at 17:54
  • 1
    Take a look at Pattern#splitAsStream() Commented Apr 8, 2016 at 17:55

2 Answers 2

4

You may use the following lambda:

Function<String, List<Integer>> collectInts = s ->
   Pattern.compile("[^0-9]+")
          .splitAsStream(s)
          .filter(p -> !p.isEmpty())
          .map(Integer::parseInt)
          .collect(Collectors.toList());

Here is used Pattern.splitAsStream() stream generator, which splits a given input by regex. Then each part is checked if it is not empty and converted to Integer.

Besides, if you need 00 instead of 0, you should not parse a number (skip Integer::parseInt mapping and collect to List<String>).

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

Comments

2

You can do:

Stream.of(f.split("[^\\d]+"))
  .filter(s -> !s.isEmpty())  // because of the split function
  .map(Integer::parseInt)
  .collect(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.