如何在 Java 中將 String 作為一個 int 流來處理


假設我們有以下字串

String str = "YuBM787Nm";

現在,若要以 IntStream 的形式顯示字串,請按以下方式使用 filter() 和 map()

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

以下是一個顯示字串為 IntStream 的示例

示例

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

輸出

String as IntStream = 166

更新於: 30-7 月-2019

98 檢視

開啟你的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.