Back to Browse

How to find Frequency (or occurrence) of characters using Java8 | Program4

430 views
Dec 11, 2024
14:03

๐…๐ซ๐ž๐ช๐ฎ๐ž๐ง๐œ๐ฒ ๐จ๐Ÿ ๐œ๐ก๐š๐ซ๐š๐œ๐ญ๐ž๐ซ๐ฌ ๐ฎ๐ฌ๐ข๐ง๐  ๐‰๐š๐ฏ๐š๐Ÿ–: ๐๐ซ๐จ๐›๐ฅ๐ž๐ฆ: Given a string and we need to find out frequency (occurrence) of each character in string. ๐’๐จ๐ฅ๐ฎ๐ญ๐ข๐จ๐ง: As we need to calculate count of characters w.r.t. each character so we need a collection which can store Character and it's respective count. So, we can utilize Map ๐‹๐ž๐ญ ๐ฎ๐ฌ ๐ฎ๐ง๐๐ž๐ซ๐ฌ๐ญ๐š๐ง๐ ๐’๐ญ๐ž๐ฉ ๐›๐ฒ ๐’๐ญ๐ž๐ฉ ๐ฎ๐ฌ๐ข๐ง๐  ๐‰๐š๐ฏ๐š๐Ÿ–: ๐’๐ญ๐ž๐ฉ๐Ÿ: Convert String in Int stream using chars() method which will give stream of ASCII value of each character ๐’๐ญ๐ž๐ฉ๐Ÿ: Convert above Int Stream in to Stream of characters with the help of mapToObj() method of stream. ๐’๐ญ๐ž๐ฉ๐Ÿ‘: use collect() terminal method to collect the final result ๐’๐ญ๐ž๐ฉ๐Ÿ’: As we need outcome in the form of Map, we will Collectors.groupingBy() method inside collect method ๐’๐ญ๐ž๐ฉ๐Ÿ“: Collectors.groupingBy() need to group same characters and then need to count each group character ๐’๐ญ๐ž๐ฉ๐Ÿ”: So Collectors.groupingBy() method will use first argument as Function.Identity() to get each char for grouping purpose and internally form ArrayList for each group of same characters ๐’๐ญ๐ž๐ฉ๐Ÿ•: Collectors.groupingBy() will use second argument as another collector to find the size of above group of individual ArrayList ๐’๐ญ๐ž๐ฉ๐Ÿ–: At last we will capture the result in Map Refer to practical demonstration below: Regards, PrinceAutomationDestination

Download

0 formats

No download links available.

How to find Frequency (or occurrence) of characters using Java8 | Program4 | NatokHD