How to approach String as int stream in Java

Java 8Object Oriented ProgrammingProgramming

Let’s say we have the following string:

String str = "YuBM787Nm";

Now to display it as IntStream, use filter() and map() as shown below:

int res = str.chars() .filter(Character::isDigit) .map(ch → Character.valueOf((char) ch)).sum();

The following is an example to display string as IntStream:

Example

public class Demo {
   public static void main(String[] args) {
      String str = "YuBM787Nm";
      int res = str.chars() .filter(Character::isDigit) .map(ch -> Character.valueOf((char) ch)).sum();
      System.out.println("String as IntStream = "+res);
   }
}

Output

String as IntStream = 166
raja
Published on 02-May-2019 07:07:09
Advertisements