Skip to content

Commit

Permalink
feat: Add most common interview question on java
Browse files Browse the repository at this point in the history
  • Loading branch information
VishwajeetVT committed Nov 19, 2024
1 parent 1e5c7fd commit 9137b33
Showing 1 changed file with 29 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package org.practice.dsa.java8.functional_programming.interview;

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

/**
* Problem: Find Duplicate Characters in a String
* Given a string, find all the duplicate characters and their counts using the Java 8 Stream API.
* The result should be a Map<Character, Integer>.
* */
public class DuplicateFromString {
public static void main(String[] args) {
System.out.println(duplicate("programming"));
}

public static Map<Character, Long> duplicate(String input) {
return input.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(
c -> c, Collectors.counting()
)).entrySet()
.stream()
.filter(entry -> entry.getValue() > 1)
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue
));
}
}

0 comments on commit 9137b33

Please sign in to comment.