-
-
Save milikkan/530f23f4d22875a583d5586983b34b32 to your computer and use it in GitHub Desktop.
A Java program that counts duplicate characters from a given string.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.HashMap; | |
import java.util.Map; | |
import java.util.stream.Collectors; | |
public class CountDuplicates { | |
// using classic for loop and Map.merge method | |
private static Map<Character, Integer> countChars(String input) { | |
var result = new HashMap<Character, Integer>(); | |
for (char ch : input.toCharArray()) { | |
result.merge(ch, 1, (a, b) -> a + b); | |
} | |
return result; | |
} | |
// using streams and collectors | |
private static Map<Character, Long> countCharsStream(String input) { | |
return input.chars() | |
.mapToObj(c -> (char) c) | |
.collect(Collectors.groupingBy(c -> c, Collectors.counting())); | |
} | |
public static void main(String[] args) { | |
String input = "çekoslavakyalılaştıramadıklarımızdanmısınız"; | |
var result1 = countChars(input); | |
var result2 = countCharsStream(input); | |
System.out.println(result1); | |
System.out.println(result2); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment