Find First Non-Repeated Character From String

Wap for Find First Non-Repeated Character From String.


Input: stress

output: t - "t" is first Non Repeated Character. I have explained through video as well. Please check out the video as well for better understanding.


 



 package org.practice.basicprgms;


import java.util.LinkedHashMap;

import java.util.Map;

import java.util.function.Function;

import java.util.stream.Collectors;


public class FindFirstNonRepeatedCharacter {


public static void main(String[] args) {

String input = "stress";

// Solution 1: using indexOf() and lastIndexOf()

Character output = input.chars() // A - 65 a 97

.mapToObj(c -> (char)c)

.filter(c -> input.indexOf(c) == input.lastIndexOf(c))

.findFirst()

.orElse(null);

System.out.println("First Non Repeated Character : "+ output);

// Solution 2 : using LinkedHashMap

output = input.chars()

.mapToObj(ch -> (char) ch)

.collect(Collectors.groupingBy(Function.identity(),

LinkedHashMap::new,

Collectors.counting()))

.entrySet()

.stream()

.filter(entry -> entry.getValue() == 1)

.map(Map.Entry :: getKey)

.findFirst()

.orElse(null);

System.out.println("First Non Repeated Character using HashMap : "+ output);

// Solution 3 : using LinkedHashMap

Map<Character, Long> charMap =

input.chars()

.mapToObj(ch -> (char) ch)

.collect(Collectors.groupingBy(Function.identity(),

LinkedHashMap::new,

Collectors.counting()));

output = charMap.entrySet().stream()

.filter(entry -> entry.getValue() == 1)

.map(Map.Entry :: getKey)

.findFirst()

.orElse(null);

System.out.println("First Non Repeated Character using HashMap second Way : "+ output);

}


}


Post a Comment

0 Comments