Sunday, 29 June 2025

10 years java springboot programming interview questions-bkp

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

  1. Thread Safety: The volatile keyword and double-checked locking ensure thread-safe instance creation.

  2. Reflection Protection: The private constructor throws an exception if an attempt is made to create another instance using reflection.

  3. Serialization Safety: The readResolve method ensures that the existing instance is returned during deserialization.

  4. 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);


Consice list-based appraoch
employees.stream().sorted(Comparator.comparing(Employee::getSalary).reversed()).limit(n).skip(n - 1).findFirst().orElse(null);

===========================
Pyramid * pattern

public class PyramidPattern {

    public static void printPyramid(int rows) {
        for (int i = 0; i < rows; i++) { // Outer loop for number of rows

            // Print spaces for indentation
            for (int j = rows - i; j > 1; j--) {
                System.out.print(" "); // You can change this to "  " for wider spacing
            }

            // Print stars
            for (int j = 0; j <= i; j++) {
                System.out.print("* "); // You can change this to "* *" for wider spacing
            }

            // Move to the next line after each row
            System.out.println();
        }
    }

    public static void main(String[] args) {
        int numRows = 5; // You can change this to any number of rows you want
        printPyramid(numRows);
    }
}


============

Sql query
SELECT salary
FROM (
    SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) as rank_num
    FROM employees
) AS ranked_salaries
WHERE rank_num = n; -- Replace n with the desired rank



SELECT DISTINCT salary
FROM employees
ORDER BY salary DESC
LIMIT 1 OFFSET (n - 1);  -- Replace n with the desired rank


SELECT DISTINCT salary
FROM employees e1
WHERE n-1 = (SELECT COUNT(DISTINCT salary) FROM employees e2 WHERE e2.salary > e1.salary);

No comments:

Post a Comment