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: 2019-07-30T22:30:25+05:30

112 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements