Find duplicate characters and number of times of duplicity using Java 8

In this post, we will see how to find duplicate characters and number of times of duplicity using Java 8.

package com.javatute.stream;

import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class DuplicateCharacter {
    public static void main(String[] args) {
        String input = "rakeshranjankumar";

        Map<Character, Long> charCountMap = input.chars()
                .mapToObj(c -> (char) c)
                .collect(Collectors.groupingBy( 
                        Function.identity(), Collectors.counting()
                ));

        charCountMap.forEach((character, count) -> {
            if (count > 1) {
                System.out.println("Character: " + character + ", Count: " + count);
            }
        });
    }
}

Output:-

Character: a, Count: 4
Character: r, Count: 3
Character: k, Count: 2
Character: n, Count: 2
  1. We convert the input string into a stream of characters using the chars() method.
  2. We then map each character to an object of type Character.
  3. We use the Collectors.groupingBy collector to group the characters by their identity (i.e., the character itself) and count their occurrences using Collectors.counting().
  4. The result is a Map<Character, Long> where the keys are the unique characters in the string, and the values are the counts of each character.
  5. We iterate through the map and print characters that have a count greater than 1, which indicates they are duplicates.

Program to count repeated String using Java 8

To find duplicate strings and count their occurrences in a collection of strings using Java 8, you can use the Stream API with the groupingBy collector. Here’s a Java program that demonstrates how to do this:

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        List<String> strings = Arrays.asList("apple", "banana", "apple", "cherry", "banana", "date", "apple");

        Map<String, Long> stringCountMap = strings.stream()
            .collect(Collectors.groupingBy(
                Function.identity(), Collectors.counting()
            ));

        stringCountMap.forEach((str, count) -> {
            if (count > 1) {
                System.out.println("String: " + str + ", Count: " + count);
            }
        });
    }
}

Output:-

String: banana, Count: 2
String: apple, Count: 3

In this program:

  1. We have a list of strings called strings.
  2. We convert the list into a stream of strings.
  3. We use the Collectors.groupingBy collector to group the strings by their identity (i.e., the string itself) and count their occurrences using Collectors.counting().
  4. The result is a Map<String, Long> where the keys are the unique strings in the list, and the values are the counts of each string.
  5. We iterate through the map and print strings that have a count greater than 1, which indicates they are duplicates.

When you run this program with the given list of strings, it will output:

String: apple, Count: 3
String: banana, Count: 2

These are the duplicate strings in the list along with their counts of duplicacy.

Program to count duplicate characters without using Java 8

We can achieve the same functionality without using Java 8 features by using older Java constructs. Here’s the equivalent code:

import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        String input = "rakeshranjankumar";

        Map<Character, Integer> charCountMap = new HashMap<>();

        // Count the characters in the string
        for (char character : input.toCharArray()) {
            if (charCountMap.containsKey(character)) {
                charCountMap.put(character, charCountMap.get(character) + 1);
            } else {
                charCountMap.put(character, 1);
            }
        }

        // Iterate through the map to find duplicates
        for (Map.Entry<Character, Integer> entry : charCountMap.entrySet()) {
            char character = entry.getKey();
            int count = entry.getValue();
            if (count > 1) {
                System.out.println("Character: " + character + ", Count: " + count);
            }
        }
    }
}

Output:-

Character: a, Count: 4
Character: r, Count: 3
Character: k, Count: 2
Character: n, Count: 2

In this code:

  1. We use a HashMap instead of the Java 8 Collectors.groupingBy collector to count the occurrences of characters in the input string.
  2. We iterate through the characters in the input string using a traditional loop.
  3. For each character, we check if it’s already in the charCountMap. If it is, we increment its count; otherwise, we add it to the map with a count of 1.
  4. After counting the characters, we iterate through the map and print characters that have a count greater than 1, which indicates they are duplicates.

This code achieves the same result as the Java 8 code you provided but without using Java 8 features.

That’s all about find duplicate characters and number of times of duplicity using Java 8.

Other Java 8 programs.