Patrykos
Patrykos

Reputation: 13

Integer from String via Lambda expression

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());};

Upvotes: 0

Views: 1287

Answers (2)

Alex Salauyou
Alex Salauyou

Reputation: 14348

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>).

Upvotes: 4

Jean Logeart
Jean Logeart

Reputation: 53839

You can do:

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

Upvotes: 2

Related Questions