Find Last duplicate character of given string using Java 8
Categories: Java 8(JDK1.8) Java Java Examples
package r4r.co.in;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class Test123 {
public static void main(String[] args) {
// Find Last duplicate character of given string using Java 8
String str = "Rajesh Kumar is Java Lead";
Map<Character, Long> mapGroupByCharacters = str.chars().mapToObj(c -> (char) c).filter(f -> f != ' ')
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println(mapGroupByCharacters);
Map<Character, Long> mapOfduplicateChacters = str.chars().mapToObj(c -> (char) c).filter(f -> f != ' ')
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting())).entrySet().stream()
.filter(f -> f.getValue() > 1).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
System.out.println(mapOfduplicateChacters);
Map<Character, Long> lastElement = mapOfduplicateChacters.entrySet().stream()
.skip(mapOfduplicateChacters.size() - 1)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
System.out.println(lastElement);
}
}
Output:-
{a=5, d=1, e=2, h=1, i=1, J=1, j=1, K=1, L=1, m=1, r=1, R=1, s=2, u=1, v=1}
{a=5, s=2, e=2}
{e=2}