Hi Friends,
In this post, we will see the program for FirstNonRepeatingCharacter in java.
package com.raj.programs;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
public class FirstNonRepeatingCharacter {
static Character getFirstNonRepeatingCharacter(String input) {
Map<Character, Integer> table = new LinkedHashMap<>(input.length());
input.chars() // IntStream
.mapToObj(c -> (char) c) // converting into char
.forEach(ch -> table.put(ch, table.containsKey(ch) ? table.get(ch) + 1 : 1)); // putting in map
return table.entrySet().stream() // getting stream from map entries
.filter(entry -> entry.getValue() == 1) // getting only the entries which presented only one time
.map(Entry::getKey) // getting the entry keys alone
.findFirst() // getting first element in the key list
.orElse(null); // If none found, null will be returned
}
public static void main(String[] args) {
System.out.println("FirstNonRepeatingCharacter :"+FirstNonRepeatingCharacter.getFirstNonRepeatingCharacter("ABCABD"));
}
}
Output:
FirstNonRepeatingCharacter :C