/** * @author lautturi.com * Java example: count occurrences of character in string java */ import java.util.*; public class Lautturi { public static void main(String[] args) { String str = "hello lautturi java world!"; long count = str.chars().filter(ch -> ch == 'a').count(); long count2 = str.codePoints().filter(ch -> ch == 'u').count(); System.out.println("a occurs "+count+" times "); System.out.println("u occurs "+count2+" times "); } }
output:
a occurs 3 times u occurs 2 times