-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Add most common interview question on java
- Loading branch information
1 parent
1e5c7fd
commit 9137b33
Showing
1 changed file
with
29 additions
and
0 deletions.
There are no files selected for viewing
29 changes: 29 additions & 0 deletions
29
...ain/java/org/practice/dsa/java8/functional_programming/interview/DuplicateFromString.java
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
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 | ||
)); | ||
} | ||
} |