Count the occurance of each char in a given Stirng
str.chars() // IntStream of character codes .mapToObj(c -> (char) c) // Convert to Stream<Character> .collect(Collectors.groupingBy( Function.identity(), // Group by the character itself Collectors.counting() // Count occurrences in each group ));
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class CharacterOccurrences {
public static Map<Character, Long> countCharacterOccurrences(String str) {
if (str == null || str.isEmpty()) {
return Map.of(); // Return empty map for null or empty string
}
return str.chars() .mapToObj(c -> (char) c) .collect(Collectors.groupingBy( Function.identity(), Collectors.counting() )); }
=======================
Final SingelTon class with all loopholes resolved
Explanation
-
Thread Safety: The
volatile
keyword and double-checked locking ensure thread-safe instance creation. -
Reflection Protection: The private constructor throws an exception if an attempt is made to create another instance using reflection.
-
Serialization Safety: The
readResolve
method ensures that the existing instance is returned during deserialization. -
Cloning Protection: The
clone
method is overridden to prevent cloning.
import java.io.Serializable; public final class Singleton implements Serializable { private static final long serialVersionUID = 1L; // Volatile instance to ensure thread safety private static volatile Singleton instance; // Private constructor to prevent instantiation private Singleton() { // Prevent reflection from creating a new instance if (instance != null) { throw new IllegalStateException("Instance already exists!"); } } // Public method to provide global access public static Singleton getInstance() { if (instance == null) { synchronized (Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; } // Prevent deserialization from creating a new instance protected Object readResolve() { return getInstance(); } // Prevent cloning @Override protected Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException("Cloning not allowed"); } // A method for demonstration public void showMessage() { System.out.println("Singleton Instance: " + this.hashCode()); } }
=============
// Java Program to Create An Immutable Class import java.util.HashMap; import java.util.Map; // declare the class as final final class Student { // make fields private and final private final String name; private final int regNo; private final Map<String, String> metadata; // initialize all fields via constructor public Student(String name, int regNo, Map<String, String> metadata) { this.name = name; this.regNo = regNo; // deep copy of mutable object (Map) Map<String, String> tempMap = new HashMap<>(); for (Map.Entry<String, String> entry : metadata.entrySet()) { tempMap.put(entry.getKey(), entry.getValue()); } this.metadata = tempMap; } // only provide getters (no setters) public String getName() { return name; } public int getRegNo() { return regNo; } // return deep copy to avoid exposing internal state public Map<String, String> getMetadata() { Map<String, String> tempMap = new HashMap<>(); for (Map.Entry<String, String> entry : this.metadata.entrySet()) { tempMap.put(entry.getKey(), entry.getValue()); } return tempMap; } }
========
public static Map<String, Map<Character, Long>> getDuplicateAndUniqueCounts(String str) { Map<Character, Long> allCounts = countCharacterOccurrences(str); Map<Character, Long> duplicates = allCounts.entrySet().stream() .filter(entry -> entry.getValue() > 1) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); Map<Character, Long> uniques = allCounts.entrySet().stream() .filter(entry -> entry.getValue() == 1) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); Map<String, Map<Character, Long>> result = new HashMap<>(); result.put("duplicates", duplicates); result.put("uniques", uniques); return result; } public static void main(String[] args) { String text = "Hello, world!"; Map<String, Map<Character, Long>> counts = getDuplicateAndUniqueCounts(text); System.out.println("Duplicates:"); counts.get("duplicates").forEach((character, count) -> System.out.println("Character: '" + character + "', Occurrences: " + count)); System.out.println("\nUniques:"); counts.get("uniques").forEach((character, count) -> System.out.println("Character: '" + character + "', Occurrences: " + count)); } }
find nth highest employee sarlary from a emlpoyee list.
Functiona based
employees.stream().map(Employee::getSalary).distinct().sorted(Comparator.reverseOrder()).skip(n-1).findFirst().orElse(null);
No comments:
Post a Comment