How to approach String as int stream in Java


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

Updated on: 30-Jul-2019

73 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements