Friday, 5 April 2013

Important Collections interview questions


You have a list of Employee objects having empNo,empName,gender,salary. 1a)Calculate the average salary of male employees using Java Streams.

1b) Filter male employees whose salary is greater than average salary

1c)Then save employee data into a CSV file in the format John,Male,50000.

1d) I want to sort the employee data based on name and then salary.

  • We have to create Employee POJO class.
  • Then we have use stream with filter and mapToDouble followed by average().
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data @NoArgsConstructor // generates no-argument constructor @AllArgsConstructor // generates all-arguments constructor public class Employee { private Integer empNo; private String empName; private String gender; private double salary; }

import java.util.Arrays; import java.util.List; public class AvgSalEmployee{ public static void main(String[] args) {
//Used var and List.of() (Java 10+).
var employees = List.of( new Employee(101,"Swamy", "Male", 50000), new Employee(102,"Pranu", "Female", 60000), new Employee(103,"Shiva", "Male", 55000), new Employee(104,"Vaisu", "Female", 65000) );
//If we use (Java 8). List<Employee> employees = Arrays.asList( new Employee(101,"Swamy", "Male", 50000), new Employee(102,"Pranu", "Female", 60000), new Employee(103,"Shiva", "Male", 55000), new Employee(104,"Vaisu", "Female", 65000) ); double avgMaleSalary = employees.stream() .filter(e -> "Male".equalsIgnoreCase(e.getGender())) .mapToDouble(Employee::getSalary) .average() .orElse(0.0); // default if no male employees System.out.println("Average Male Salary: " + avgMaleSalary);

// 1b: Filter employees whose salary > avgSalary
List<Employee> aboveAvgEmployees = lst.stream()
    .filter(e -> e.getSalary() > avgMaleSalary)
    .collect(Collectors.toList());

// Optional: Print or sort
aboveAvgEmployees.forEach(System.out::println);

//1c)To save employee data into a CSV file in the format Swamy,Male,50000, you can //use Files.write with a simple stream in Java
 // Save to CSV
        Path filePath = Path.of("employees.csv");
        List<String> csvLines = employees.stream()
            .map(e -> String.format("%s,%s,%s,%.2f", e.getEmpNo(), e.getEmpName(), e.getGender(), e.getSalary()))
            .toList();

        Files.write(filePath, csvLines);
        System.out.println("CSV file saved at: " + filePath.toAbsolutePath());
} }
Notes:
  • filter: to select only male employees.

  • mapToDouble: to extract salary.

  • average(): returns OptionalDouble.

  • orElse(0.0): handles the case when no male employees are present.

// 1d) I want to sort name and then salary
List<Employee> sortedList = employees.stream()
    .sorted(Comparator.comparing(Employee::getEmpName)
            .thenComparing(Employee::getSalary))
    .collect(Collectors.toList());

sortedList.forEach(System.out::println);
๐Ÿ” Explanation:
a)Comparator.comparing(Employee::getEmpName) → sorts by name.
b)thenComparing(Employee::getSalary) → if names are equal, sorts by salary.

-------------------------------------

2) Use Stream API to filter employee by empno

import java.util.Arrays;

import java.util.List;

import java.util.Optional;


public class EmployeeSearch {

public static void main(String[] args) {

List<Employee> employees = Arrays.asList(

       new Employee(101,"Swamy", "Male", 50000),

new Employee(102,"Pranu", "Female", 60000), new Employee(103,"Shiva", "Male", 55000), new Employee(104,"Vaisu", "Female", 65000)

);


int searchEmpNo = 102;


Optional<Employee> result = employees.stream()

.filter(emp -> emp.getEmpno() == searchEmpNo)

.findFirst();


if (result.isPresent()) {

System.out.println("Employee found: " + result.get());

} else {

System.out.println("Employee not found with empno: " + searchEmpNo);

}

}

}

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

3) What is output? Why? explain correct version

a)Stream<Integer> s1 = alist.stream();  ❌ Not reusable after terminal op

b)List<Integer> l1 = s1.sorted().skip(4).Collectors.toList(); // ❌ wrong Collectors.toList() should be used with .collect(...), not directly after .skip(...).

c)s1.distinct().collect(Collectors.toList()); // ❌ reusing stream Once a terminal operation (like .collect(...)) is called, the stream is consumed and cannot be used again.

d)s1.filter(s -> s % 2 == 0).collect(Collectors.toList()); // ❌ again reusing
a
✅ Correct Version:
List<Integer> list = new ArrayList<>(alist); // reuse possible

List<Integer> sortedList = alist.stream()
                                .sorted()
                                .skip(4)
                                .collect(Collectors.toList());

List<Integer> distinctList = alist.stream()
                                  .distinct()
                                  .collect(Collectors.toList());

List<Integer> evenList = alist.stream()
                              .filter(s -> s % 2 == 0)
                              .collect(Collectors.toList());

✅ Explanation:

  • alist.stream(): A new stream must be created each time because Java streams are single-use.

  • .sorted().skip(4): Sorts the list and skips the first 4 elements.

  • .collect(Collectors.toList()): Collects the resulting stream into a List.


4) What is the output for below?
String s1 ="abc"; 
String s2;//Some api call returning some value 
if(s2==s1) 
System.out.println("s1 and s2 are true"); 
s2.equals(s1);

❗ Issues:

  1. s2 is declared but never initialized:

    • This will result in a compilation error: "variable s2 might not have been initialized."

  2. Using == to compare strings:

    • == compares object references, not actual content. Use .equals() for content comparison.

  3. Potential NullPointerException:

    • If s2 is null, then s2.equals(s1) will throw a runtime error.


✅ Corrected Code:

String s1 = "abc"; String s2 = someApiCall(); // assume this returns a String, possibly null // Safely compare strings using .equals() if (s1.equals(s2)) { System.out.println("s1 and s2 are equal by content"); } // or reverse it to avoid NPE if s2 might be null if ("abc".equals(s2)) { System.out.println("s2 equals 'abc'"); }

✅ Safer Practice

๐Ÿ”’ Null-safe string comparison:

if ("abc".equals(s2)) { // safe even if s2 is null }

This avoids NullPointerException if s2 is null, since the literal string "abc" is definitely not null.


๐Ÿงช Summary: String Comparison in Java

ExpressionWhat It Does
s1 == s2Compares references (same memory address)
s1.equals(s2)Compares string contents
"abc".equals(s2)Null-safe content comparison

5) Example: Print 1 to 100 with Lambda

import java.util.stream.IntStream;

public class LambdaPrintExample {
    public static void main(String[] args) {
        IntStream.rangeClosed(1, 100)
                 .forEach(n -> System.out.println(n));
    }
}

import java.util.*;
import java.util.stream.*;

public class LambdaListExample {
    public static void main(String[] args) {
        // Create a List of integers from 1 to 100
        List<Integer> numbers = IntStream.rangeClosed(1, 100)
                                         .boxed()  // Convert IntStream to Stream<Integer>
                                         .collect(Collectors.toList());

        // Print each number using a lambda
        numbers.forEach(n -> System.out.println(n));
    }
}
Explanation:
IntStream.rangeClosed(1, 100) → Creates a stream of primitive ints from 1 to 100 (inclusive).
.boxed() → Converts each int to Integer (autoboxing), so you can store it in a List<Integer>.
.collect(Collectors.toList()) → Collects the stream into a list.

6)stream() Internal Mechanism lazy loading and eagar loading

๐Ÿง  What is .stream()?

stream() is a default method in the java.util.Collection interface that allows a collection (like List, Set, etc.) to produce a sequential Stream:

default Stream<E> stream() {
return StreamSupport.stream(spliterator(), false); }

So when you call:

List<String> list = Arrays.asList("apple", "banana", "cherry"); Stream<String> sstr= list.stream();

Internally, the above line actually invokes:

StreamSupport.stream(list.spliterator(), false);

What is a Stream?

A Stream is a sequence of elements supporting sequential and parallel aggregate operations.

Think of it like a pipeline where data flows through a series of operations.

✅ 1. Stream Internal Mechanism Overview

In Java 8+, the Stream API is built on top of the pull-based model using Spliterator, intermediate and terminal operations.

The key design philosophy is lazy evaluation.

✅ 2. Lazy Loading (Lazy Evaluation)

Definition:
Stream operations like filter(), map(), sorted(), etc. are lazy — they do not execute immediately.

Instead, they create a pipeline of transformations that are executed only when a terminal operation (like collect(), forEach(), count()) is invoked.

๐Ÿ” Example:

List<String> list = Arrays.asList("apple", "banana", "cherry");
Stream<String> sstr= list.stream() .filter(s -> { System.out.println("Filtering: " + s); return s.startsWith("a"); }); // No output yet! sstr.forEach(System.out::println); // Now executes the filter lazily

๐Ÿ” Output:

Filtering: apple
apple Filtering: banana Filtering: cherry

✅ Notice: filter() is executed only when forEach() is calledLazy Evaluation

✅ 3. Eager Loading

Definition: Eager operations are those that are executed immediately. In Java Streams, only terminal operations (like forEach(), collect(), count(), etc.) are eager.

๐Ÿ” Example:

List<String> list = Arrays.asList("a", "b", "c"); long count = list.stream() .filter(s -> { System.out.println("filtering: " + s); return true; }) .count(); // Triggers the stream execution

✅ Once count() is called, it eagerly processes the pipeline

✅ 4. Internal Components of a Stream

ComponentDescription
SpliteratorSplits the source data and allows parallel traversal
Intermediate Operatione.g., map, filter, sortedlazy
Terminal Operatione.g., forEach, collect, reduceeager
PipelineInternally streams are modeled as a chain (linked list) of pipeline stages
StreamPipeline.HeadThe source (list, array, etc.)
StreamPipeline.StatefulOpSome intermediate operations like distinct, sorted that store state
StreamPipeline.TerminalOpThe end of the pipeline, initiates processing

✅ 5. Lazy vs Eager: How Execution Flows

๐Ÿš€ Stream Pipeline (Lazy Until Terminal):

java
Stream<T> = Source + Intermediate Operations (lazy) + Terminal Operation (eager)

Execution happens as a pull-based chain (like UNIX pipes):

  • Terminal op pulls data → intermediate ops process → source supplies data

✅ 6. Optimization: Short-Circuiting

Some operations (like anyMatch, findFirst) are short-circuiting — they can terminate early without processing all elements.

java
Stream.of("one", "two", "three") .filter(s -> { System.out.println("Filtering: " + s); return s.startsWith("t"); }) .findFirst(); // stops after "two"

✅ Summary Table

Operation TypeExamplesExecution
Intermediate (lazy)filter(), map(), sorted()Deferred
Terminal (eager)forEach(), collect(), count()Immediate
Stateful Intermediatedistinct(), sorted()Stores previous state
Short-circuitinglimit(), anyMatch()Stops early

✅ Visual of Stream Pipeline

text
[List] → [filter()] → [map()] → [limit()] → [collect()] (lazy) (lazy) (short) (eager)

Each step is built, but not executed until the terminal step triggers the pipeline.

✅ Step 1: stream() in Collection Interface

Defined in java.util.Collection:

default Stream<E> stream() { return StreamSupport.stream(spliterator(), false); }

Here:

  • spliterator() is a method from the Iterable interface.

  • false means we want a sequential stream (not parallel).


✅ Step 2: spliterator() Method

Every collection provides its own implementation of spliterator().

For example:

public class ArrayList<E> extends AbstractList<E> { public Spliterator<E> spliterator() { return new ArrayListSpliterator<>(this, 0, -1, 0); } }

A Spliterator is like a modern iterator with additional capabilities:

  • Can split the collection into parts (useful for parallel processing).

  • Supports characteristics like SIZED, ORDERED, etc.


✅ Step 3: StreamSupport.stream(...)

From java.util.stream.StreamSupport:

public static <T> Stream<T> stream(Spliterator<T> spliterator, boolean parallel) { Objects.requireNonNull(spliterator); return new ReferencePipeline.Head<>(spliterator, StreamOpFlag.fromCharacteristics(spliterator), parallel); }

๐Ÿ”ธ What is happening here?

  • The stream() method constructs a pipeline starting with the Head stage.

  • ReferencePipeline.Head<T> is the starting point of the stream processing pipeline.


⚙️ ReferencePipeline.Head (Source Stage)

๐Ÿ” Code Snippet:

static class Head<E_IN, E_OUT> extends ReferencePipeline<E_IN, E_OUT> { Head(Spliterator<?> source, int sourceFlags, boolean parallel) { super(source, sourceFlags, parallel); } @Override final boolean opIsStateful() { throw new UnsupportedOperationException(); } @Override final Sink<E_IN> opWrapSink(int flags, Sink<E_OUT> sink) { throw new UnsupportedOperationException(); } }

It represents:

  • The source of elements (from Spliterator).

  • The starting node in the stream pipeline.

  • Whether the stream is parallel or not.


๐Ÿ” What Happens Next?

After .stream() is called:

  • The stream pipeline is constructed (intermediate operations like filter, map wrap the pipeline).

  • But no operation is executed yet!

Only when a terminal operation like .collect(), .forEach(), .reduce() is called does the pipeline trigger execution.


๐Ÿ“Š Internal Stream Pipeline Architecture

Visual Representation:

plaintext

List -> spliterator() -> StreamSupport.stream() -> ReferencePipeline.Head | +-> Intermediate Ops (filter, map, etc.) | +-> Terminal Op (collect, reduce, forEach)

๐Ÿงฉ Key Classes in Internals

ClassDescription
Collection.stream()Entry point from collections
Iterable.spliterator()Produces a Spliterator
StreamSupport.stream()Builds pipeline head
ReferencePipeline.HeadFirst stage of the stream
AbstractPipelineBase for intermediate/terminal operations
SpliteratorSource traverser/splitter
SinkAccepts and processes elements in pipeline stages

๐Ÿ”ฌ Real Example with Debug (Stream not executed immediately)

List<String> list = Arrays.asList("apple", "banana", "cherry"); Stream<String> stream = list.stream() .filter(s -> { System.out.println("Filtering: " + s); // Lazy! return s.startsWith("a"); }); System.out.println("No terminal operation yet..."); // No output seen from filter lambda! stream.collect(Collectors.toList()); // Triggers execution

✅ Summary

ComponentDescription
.stream()Default method in Collection, delegates to StreamSupport.stream(...)
spliterator()Obtains an efficient traverser/splitter from the collection
StreamSupport.stream()Constructs pipeline head (ReferencePipeline.Head)
ReferencePipelineRepresents lazy stages of the stream
Terminal operationTriggers actual traversal and processing

๐Ÿง  Bonus: Parallel Streams

If you call .parallelStream() instead of .stream():

default Stream<E> parallelStream() { return StreamSupport.stream(spliterator(), true); }

The true tells the pipeline to:

  • Enable parallel execution.

  • Use ForkJoinPool.commonPool() for multi-threaded processing.

7) How many ways calls garbage collector

In Java, Garbage Collection (GC) is mostly automatic, but there are several ways to request or influence the garbage collector, though it is not guaranteed that it will run immediately.

There are 6 main ways to request or influence the Java Garbage Collector:

๐Ÿ” 1. Using System.gc()


System.gc();
  • Suggests that the JVM perform garbage collection.

  • It calls Runtime.getRuntime().gc() internally.

  • Not guaranteed — JVM may ignore it.


๐Ÿ” 2. Using Runtime.getRuntime().gc()

Runtime.getRuntime().gc();
  • Similar to System.gc(), but called explicitly through the Runtime object.

  • Also just a request to the JVM.


๐Ÿ” 3. Calling System.runFinalization()

System.runFinalization();
  • Suggests that the JVM run finalizers on objects pending finalization.

  • Often used with System.gc().

Example:

System.gc(); System.runFinalization();

⚠️ Deprecated or discouraged in many cases because of unpredictable behavior.


๐Ÿ” 4. Using finalize() Method (Deprecated)

@Override protected void finalize() throws Throwable { System.out.println("Object is garbage collected"); }
  • JVM might call this before reclaiming the object.

  • Deprecated in Java 9+, and removed in Java 18+.

  • Should not be used in new code.


๐Ÿ” 5. Nullifying References (Encouraging GC)


MyObject obj = new MyObject(); obj = null; // eligible for GC
  • By removing strong references to an object, it becomes eligible for GC.

  • Actual collection depends on JVM.


๐Ÿ” 6. Using PhantomReference, SoftReference, or WeakReference

These are classes in java.lang.ref package used to:

Reference TypeBehavior
SoftReferenceCleared at low memory
WeakReferenceCleared at next GC cycle
PhantomReferenceEnqueued after object finalized

Example:
WeakReference<MyObject> weakRef = new WeakReference<>(new MyObject());
  • Helps track or influence GC for caching and cleanup purposes.


๐Ÿšซ What You Cannot Do:

  • You cannot force GC to run at a specific time.

  • You cannot control the exact object removal timing.

  • JVM vendors have different GC implementations and optimizations.


๐Ÿ“Œ Summary Table

WayMethodGuaranteed?
1System.gc()❌ No
2Runtime.getRuntime().gc()❌ No
3System.runFinalization()❌ No
4finalize()❌ No (Deprecated)
5Nullifying reference❌ No
6Reference types (WeakReference, etc.)❌ No

๐Ÿงช Bonus: JVM Options to Control GC Behavior

You can use JVM flags to influence GC algorithms and behavior:

-XX:+UseG1GC -XX:+PrintGCDetails -XX:+UseParallelGC -XX:+UseConcMarkSweepGC

8)Covariant Return Types in Java

In Java, a covariant return type allows an overridden method to return a subclass of the object returned by the overridden method in the parent class.

๐Ÿ”ธ In simpler words:

The return type of an overriding method can be a subtype (child) of the return type declared in the overridden method.


๐Ÿ” Why Useful?

It allows more specific return types in subclass methods, enabling more flexibility and type safety in object-oriented design.


๐Ÿงช Example

๐Ÿ”น Parent Class

class Animal { public Animal makeSound() { System.out.println("Animal makes a sound"); return new Animal(); } }

๐Ÿ”น Child Class with Covariant Return

class Dog extends Animal { @Override public Dog makeSound() { // Covariant return type (Dog extends Animal) System.out.println("Dog barks"); return new Dog(); } }

✅ Main Method to Run

public class TestCovariantReturn { public static void main(String[] args) { Animal a = new Animal(); a.makeSound(); // Output: Animal makes a sound Dog d = new Dog(); d.makeSound(); // Output: Dog barks Animal ad = new Dog(); ad.makeSound(); // Output: Dog barks (polymorphism with covariant return) } }

  • makeSound() in Animal returns an Animal.
  • makeSound() in Dog overrides that method but returns a more specific type: Dog.

  • This is type-safe and allowed due to covariant return types.

⚖️ Rules of Covariant Return Types

RuleDescription
Must override a method from a superclass.
The return type must be a subtype (child class) of the original method's return type.
Not allowed for primitive types (e.g., int vs float).
Doesn't apply to method parameters — only return types.
9) Time Complexity of ArrayList Operations in Java

✅ Time Complexity of ArrayList in Java — Detailed Breakdown

ArrayList is part of the Java Collections Framework and is backed by a dynamic array. This means it offers fast access but can be slower for some insert/remove operations compared to linked structures.


๐Ÿ“Š ArrayList Time Complexity Table

Operation Time Complexity Explanation
add(E e) (at end) O(1) (Amortized) Fast unless resizing is needed
add(int index, E element) O(n) Worst-case: shifting elements to the right
get(int index) O(1) Direct access via index
set(int index, E element) O(1) Replaces element at index
remove(int index) O(n) Elements are shifted left
remove(Object o) O(n) May require scanning and shifting
contains(Object o) O(n) Linear search
indexOf(Object o) O(n) Linear search
clear() O(n) Nulls all elements for GC
size() O(1) Just returns internal size variable
iterator() / listIterator() O(1) Lightweight creation
ensureCapacity(int minCap) O(n) (copying) Resizes internal array
trimToSize() O(n) (copying) Shrinks internal array

๐Ÿง  Key Notes

✅ Amortized O(1) for add(E e)

  • Internally, if array capacity is full, it resizes (usually by 1.5x).

  • Resize involves copying all elements to a new array → O(n)

  • But since it doesn't happen every time, the average over time is O(1).

๐Ÿ”„ remove(int index)

  • Removing shifts elements to the left.

for (int i = index; i < size - 1; i++) { elementData[i] = elementData[i + 1]; }
  • Hence, O(n) in the worst case (if removing from beginning).


✅ Best Use Cases for ArrayList

ScenarioRecommended?Reason
Frequent random access✅ YesFast get() and set()
Frequent additions at end✅ YesAmortized O(1)
Frequent insertion/removal at middle/start❌ NoCostly shifting (O(n))

๐Ÿš€ Internals Recap (How ArrayList Works)

  • Uses a backing array: Object[] elementData.

  • Tracks current number of elements: int size.

  • Resizes itself using:


newCapacity = oldCapacity + (oldCapacity >> 1); // i.e., 1.5x

10)Load Factor in Java Collections

Load Factor in Java Collections (especially in HashMap, HashSet, and LinkedHashMap) determines
when the capacity of a hash-based collection should be increased to maintain performance.

๐Ÿ“˜ Definition

Load Factor is a measure of how full the hash table is allowed to get before it is resized (rehashing occurs).

๐Ÿ”ข Default Load Factor Value

final float DEFAULT_LOAD_FACTOR = 0.75f; This means: When 75% of the bucket array is filled, The capacity is doubled, And all keys are rehashed into a new bucket array.

๐Ÿง  Formula

threshold = capacity * loadFactor threshold: when the resize will happen. capacity: size of the bucket array. loadFactor: the defined threshold fraction. Example: capacity = 16 (default) loadFactor = 0.75 threshold = 16 * 0.75 = 12 So when the 13th entry is inserted, rehashing (resize) will occur.

๐Ÿ—️ Constructor with Load Factor

You can specify it in constructors: Map<String, String> map = new HashMap<>(16, 0.5f); Initial capacity: 16 Load factor: 0.5 → threshold = 8

๐Ÿ“ˆ Why Important?

Load Factor Impact ✅ Lower (e.g., 0.5) Faster lookup, but uses more memory ⚠️ Higher (e.g., 0.9) Saves memory, but increases collisions and slows down lookup

๐Ÿ” Affects Which Collections?

Collection Uses Load Factor? HashMap ✅ Yes LinkedHashMap ✅ Yes HashSet ✅ Yes (internally uses HashMap) Hashtable ✅ Yes TreeMap, ArrayList, LinkedList ❌ No (they use other mechanisms)

⚠️ Load Factor ≠ Capacity

Capacity is the number of buckets in the table. Load Factor controls when to increase the capacity.

๐Ÿงช Internal Working in HashMap (simplified):

if (size >= threshold) resize(); // Doubles capacity and rehashes

๐Ÿ“Œ Summary

Term Meaning Load Factor Fraction of how full the table can get before resizing Default 0.75 Effect Controls memory vs performance trade-off Resize Trigger When size >= capacity * loadFactor

12) find the max length of the string and it's count in the given
String[] s = {"i", "am", "learning", "springboot"};
or
List<String> list = List.of("i", "am", "learning", "springboot");

import java.util.Arrays;

import java.util.Collections;

import java.util.Comparator;

import java.util.List;

import java.util.Optional;


public class MaxLengthWordInStringArray {

public static void main(String[] args) {

List<String> lst = Arrays.asList("i", "am", "learning", "springboot");

//Example1 using stream().max()

String maxLengthName = lst.stream()

.max(Comparator.comparingInt(String::length))

.orElse("No names");

System.out.println("Name with max length: " + maxLengthName);

//Example2 using stream() and Optional class and Comparator.comparing()

Optional<String> maxStr2 = lst.stream().max(Comparator.comparing(String::length));

maxStr2.ifPresent(s -> {

System.out.println("Max String: " + s);

System.out.println("Length: " + s.length());

});

//Example3 // Using Collections.max()

String maxStr = Collections.max(lst, Comparator.comparing(String::length));


// Print the result

System.out.println("Max String: " + maxStr);

System.out.println("Length: " + maxStr.length());


}

}


13)find the length of the longest substring without repeating characters.
Input: String s = "abcabcbb"
Output: the answer is "abc", with the length of 3.

✅ Java Code Using Sliding Window:

import java.util.HashSet; import java.util.Set; public class LongestSubstringInString { public static void main(String[] args) { String s = "abcabcbb"; String result = longestUniqueSubstring(s); System.out.println("Longest substring without repeating characters: \"" + result + "\""); System.out.println("Length: " + result.length()); } public static String longestUniqueSubstring(String s) { Set<Character> set = new HashSet<>(); int left = 0, maxLen = 0, startIndex = 0; for (int right = 0; right < s.length(); right++) { while (set.contains(s.charAt(right))) { set.remove(s.charAt(left)); left++; } set.add(s.charAt(right)); if (right - left + 1 > maxLen) { maxLen = right - left + 1; startIndex = left; } } return s.substring(startIndex, startIndex + maxLen); } }

✅ Java 8 Solution (Sliding Window using Map<Character, Integer>)

This version uses a Map to track the last index of each character and jumps the start pointer when duplicates are found — a more efficient O(n) solution.

import java.util.*; public class LongestSubstringJava8 { public static void main(String[] args) { String s = "abcabcbb"; Map<Character, Integer> map = new HashMap<>(); int maxLen = 0; int start = 0; String result = ""; for (int end = 0; end < s.length(); end++) { char c = s.charAt(end); if (map.containsKey(c)) { // Move the start pointer to the right of the last duplicate start = Math.max(map.get(c) + 1, start); } map.put(c, end); // update latest index of char int windowLen = end - start + 1; if (windowLen > maxLen) { maxLen = windowLen; result = s.substring(start, end + 1); } } System.out.println("Longest substring without repeating characters: " + result); System.out.println("Length: " + maxLen); } }
14)Sample program for HashMapKeyValue
package collections;
import java.util.Map;
import java.util.HashMap;

public class HashMapKeyValue {
    public static void main(String[] args) {
        // Scenario: Using immutable Map.of (Java 9+)
        Map<Integer, String> immutableMap = Map.of(10, "swamy", 20, "narayan", 30, "raj");
        System.out.println("Immutable Map:");
        immutableMap.forEach((k, v) -> System.out.println(k + "....." + v));

        // Scenario: Using mutable HashMap
        Map<Integer, String> mutableMap = new HashMap<>();
        mutableMap.put(10, "swamy");
        mutableMap.put(20, "narayan");
        mutableMap.put(30, "raj");

        System.out.println("\nMutable Map:");
        mutableMap.forEach((k, v) -> System.out.println(k + "....." + v));

        // Using stream for entries
        System.out.println("\nUsing Stream (entrySet):");
        mutableMap.entrySet().stream()
                  .forEach(e -> System.out.println(e.getKey() + "....." + e.getValue()));

        // Print only keys
        System.out.println("\nKeys:");
        mutableMap.keySet().forEach(System.out::println);

        // Print only values
        System.out.println("\nValues:");
        mutableMap.values().forEach(System.out::println);
    }
}

=======================================================================
17)Sample program for HashCodeDemo
public class HashCodeDemo {
    private final int i;

    public HashCodeDemo(int i) {
        this.i = i;
    }

    @Override
    public int hashCode() {
        return Integer.hashCode(i); // more robust than returning i directly
    }

    @Override
    public String toString() {
        return String.valueOf(i);
    }

    public static void main(String[] args) {
        HashCodeDemo h1 = new HashCodeDemo(100);
        HashCodeDemo h2 = new HashCodeDemo(110);

        System.out.println(h1); // 100
        System.out.println(h2); // 110
    }
}

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

18)Sample program for ArrayListSortSublist

import java.util.Arrays;

import java.util.List;

import java.util.stream.Collectors;


public class ArrayListSortSublist {

public static void main(String[] args) {

// Create a mutable ArrayList from an immutable List.of(...)

List<Integer> list = new ArrayList<>(List.of(10, 6, 8, 4, 2, 5, 1, 3, 7, 9, 82, 42));

list.sort(Integer::compareTo); // or Collections.sort(list)

System.out.println("Sorted List: " + list);

// Print elements from index 4 to 9 (inclusive)

list.subList(4, 10).forEach(System.out::println);


List<Integer> lst = Arrays.asList(10, 6, 8, 4, 2, 5, 1, 3, 7, 9, 82, 42);

List<Integer> list2 = lst.stream().sorted().collect(Collectors.toList());

System.out.println("Sorted List: " + list2);

// Print elements from index 4 to 9 (inclusive)

list2.subList(4, 10).forEach(System.out::println);


}

}


19) Find common elements from 2 arrays


import java.util.Arrays;

import java.util.List;

import java.util.stream.Collectors;


public class CommonElementsin2Arrays {

public static void main(String[] args) {

Integer[] array1 = {1, 2, 3, 4, 5};

Integer[] array2 = {3, 4, 5, 6, 7};


List<Integer> common = Arrays.stream(array1)

.filter(num -> Arrays.asList(array2).contains(num))

.distinct()

.collect(Collectors.toList());


System.out.println("Common Elements: " + common);

}

}


20)Get the distinct characters with order and their count using stream()

import java.util.List;

import java.util.stream.Collectors;

public class DistinctCharsAndCount { public static void main(String[] args) { String str = "CCBBGHjdfhddf"; List<Character> distinctChars = str.chars() // Convert to IntStream of characters .mapToObj(c -> (char) c) // Convert int to Character .distinct() // Get distinct characters (preserves order) .collect(Collectors.toList()); // Collect to list
long distinctCharsCount = str.chars() // Convert to IntStream of characters .mapToObj(c -> (char) c) // Convert int to Character .distinct() // Get distinct characters (preserves order) .count();
System.out.println("Distinct characters in order: " + distinctChars); //[C, B, G, H, j, d, f, h]
System.out.println("Distinct characters in order: " + distinctCharsCount); //8 } }

๐Ÿ” Explanation:

str.chars() → returns IntStream of Unicode values. .mapToObj(c -> (char) c) → convert each Unicode int to Character. .distinct() → filters out duplicates but retains the original order. .collect(Collectors.toList()) → collects results into a list.

21) How to get distinct characters and their count in a String?


import java.util.Map;

import java.util.function.Function;

import java.util.stream.Collectors;


public class EachCharactersAndTheirCounts {

public static void main(String[] args) {

String str= "programming";


Map<Character, Long> charCountMap = str.chars().mapToObj(c -> (char) c)

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


System.out.println("Distinct Characters and Counts: " + charCountMap); //{p=1, a=1, r=2, g=2, i=1, m=2, n=1, o=1}

}

}

22. java 8 -> count occurrences of the characters in given string

Example1 : Countcharacters using Function

import java.util.Map;

import java.util.function.Function;

import java.util.stream.Collectors;


public class CountCharacters1 {


public static void main(String[] args) {

String str= "AAABBB";

Map<Character, Long> charCount = str.codePoints().mapToObj(Character::toString)

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

System.out.println("Each Characters and Counts: " + charCount);

}


}


Example2 : Countcharacters using getOrDefault method
import java.util.HashMap; import java.util.Map; public class CountCharacters2 { public static void main(String[] args) { String str= "AAABBBcccc"; Map<Character, Integer> charCount = new HashMap<>(); for (Character ch : str.toCharArray()) { charCount.put(ch, charCount.getOrDefault(ch, 0) + 1); // Increment count or initialize to 1 } System.out.println(charCount); } }

23)Remove all duplicates and also exclude any numeric strings using stream

List<String> lst = Arrays.asList("abc","123","456","abc","ads");

import java.util.Arrays;

import java.util.List;

import java.util.stream.Collectors;


public class RemoveDuplicExcludeInt {

public static void main(String[] args) {

List<String> lst = Arrays.asList("abc", "123", "456", "abc", "ads");


List<String> result = lst.stream()

.filter(s -> !s.matches("\\d+")) // Exclude numeric strings

.distinct() // Remove duplicates

.collect(Collectors.toList()); // Collect to list


System.out.println("Distinct elements: " + result);

}

}


24: the sum of the squares of all odd numbers in a given list using Java 8's Streams API with parallel execution
Given : List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); The code should generate the following result. 1²+3²+5²=35

import java.util.Arrays; import java.util.List; public class SquaresOfOdd{ public static void main(String[] args) { List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); int sum = numbers.parallelStream() .filter(n -> n % 2 == 1) .map(n -> n * n) .reduce(0, Integer::sum); System.out.println(sum); } }


27: Write a program to find employeename Groupby doj 


import java.time.LocalDate;

import java.util.Arrays;

import java.util.List;

import java.util.Map;

import java.util.stream.Collectors;


class Employee1 {

private String name;

private LocalDate doj;


public Employee1(String name, LocalDate doj) {

this.name = name;

this.doj = doj;

}


public String getName() {

return name;

}


public LocalDate getDoj() {

return doj;

}


@Override

public String toString() {

return name;

}

}


public class GroupByDOJ {

public static void main(String[] args) {

// Sample employee data

List<Employee1> employees = Arrays.asList(

new Employee1("swamy", LocalDate.of(2021, 5, 15)),

new Employee1("Pranu", LocalDate.of(2020, 3, 20)),

new Employee1("Vaisu", LocalDate.of(2021, 5, 15)),

new Employee1("Srihan", LocalDate.of(2020, 3, 20)),

new Employee1("Raju", LocalDate.of(2019, 8, 10))

);


// Group employee names by DOJ

Map<LocalDate, List<String>> groupedByDOJ = employees.stream()

.collect(Collectors.groupingBy(

Employee1::getDoj, // Group by DOJ

Collectors.mapping(Employee1::getName, // Collect names

Collectors.toList()) // Collect into a list

));


// Print the grouped data

groupedByDOJ.forEach((doj, names) -> {

System.out.println("DOJ: " + doj + " -> Employees: " + names);

});

}

}


28: Write a program to remove the symbol [ from the string in Java

Srting str=This[Is[A[String


Using String.replace():


public class RemoveSymbol1 {

public static void main(String[] args) {

String str = "This[Is[A[String";

// Remove all occurrences of '['

String result = str.replace("[", "");

System.out.println(result);

}

}


Using String.replaceAll():


public class RemoveSymbol2 {

public static void main(String[] args) {

String str = "This[Is[A[String";

// Remove all occurrences of '[' using regex

String result = str.replaceAll("\\[", "");

System.out.println(result);

}

}


29: Write a program to add the symbol [ before every uppercase letter in the string using replaceAll()

String str="ThisIsAString"


public class AddSymbolBeforeCapsUsingString{

public static void main(String[] args) {

String str = "ThisIsAString";


// Add "[" before each uppercase letter

String result = str.replaceAll("([A-Z])", "[$1");


System.out.println(result);

}

}

30. What is the output for given code? String s = "test"; s.concat("java"); System.out.println(s);


Output: test

Because String is immutable in Java.


31. Can i extends FI1 with FT2?

@FunctionalInterface interface I2 { void show(); } @FunctionalInterface interface I1 extends I2 { void display(); // ❌ Now I1 has two abstract methods: show() + display() }

Ans: No


32. What is the output for given code?

class A {

void show() {

System.out.println("Inside A: show()");

}

}


class B extends Main {

void display() {

System.out.println("Inside B: display()");

}

}


class Main {

public static void main(String[] args) {

B a = new B();

}

}


Output: (no output)


33) Remove duplicates words from List
import java.util.*;

import java.util.stream.Collectors;

public class RemoveDupWordsFromList {
    public static void main(String[] args) {
        List<String> li = Arrays.asList("three", "one", "two", "one", "one");

        // Using Stream to remove duplicates (preserves insertion order)
        List<String> uniqueList = li.stream()
                                    .distinct()
                                    .collect(Collectors.toList());

        // Print using method reference
        uniqueList.forEach(System.out::println);
    }
}

35)How to swap two numbers without using a third variable?

public class swap {

public static void main(String[] args) {

int a = 10, b = 20;

a = a+b;

b =a-b;

a = a-b;

System.out.println(a);

System.out.println(b);

}

} 36)Separate vowels and consonants from given string


import java.util.Arrays;

import java.util.List;

import java.util.Set;

import java.util.stream.Collectors;


public class SeparateVowCon {


public static void main(String[] args) {

String str = "Hi this is swamy, separating vowels and consonants";

List<Character> vowels = Arrays.asList('a','e','i','o','u');

Set<Character> charSet = str.chars().mapToObj(e->(char)e).collect(Collectors.toSet());

List<Character> listVowels = charSet.stream().filter(ch->vowels.contains(ch.toLowerCase(ch))).collect(Collectors.toList());

List<Character> listConsonants = charSet.stream().filter(ch->!vowels.contains(ch.toLowerCase(ch))).collect(Collectors.toList());

System.out.println("The listVowels"+listVowels);

System.out.println("The listConsonants"+listConsonants);

}

}

37)Java program to check if the given number is Prime


import java.util.Scanner;


public class PrimeNumberOrNot {

public static void main(String args[]) {

int i, m = 0, flag = 0;

Scanner sc = new Scanner(System.in);

System.out.println("Enter the integer:");

int number = sc.nextInt();

m = number / 2;

if (number == 0 || number == 1) {

System.out.println(number + " is not prime number");

} else {

for (i = 2; i <= m; i++) {

if (number % i == 0) {

System.out.println(number + " is not prime number");

flag = 1;

break;

}

}

if (flag == 0) {

System.out.println(number + " is prime number");

}

} // end of else

}

}

38a)Check given string is palindrome or not


public class StringPalindromeOrNot {

public static void main(String args[]) {


// Scanner sc=new Scanner(System.in);

// System.out.println("Please enter string: ");

// String str=sc.nextLine();

String str = "strts";

String revstr = "";

for (int i = str.length()- 1; i >= 0; i--)

revstr = revstr + str.charAt(i);

if (str.equals(revstr))

System.out.println(str + " is a palindrome.");

else

System.out.println(str + " is not a palindrome.");

}

}



38b)Check given number is palindrome or not


import java.util.Scanner;


public class NumberPalindromeOrNot {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("Enter any number:");

int n = sc.nextInt();

sc.close();


if (isPalindrome(n)) {

System.out.println("Palindrome");

} else {

System.out.println("Not a palindrome");

}

}


private static boolean isPalindrome(int n) {

int original = n;

int reversed = reverseNumber(n);

return original == reversed;

}


private static int reverseNumber(int n) {

int reversed = 0;

while (n > 0) {

reversed = reversed * 10 + n % 10;

n /= 10;

}

return reversed;

}

}


39)Print number of largest polindrome in a string

import java.util.Scanner;


public class LargestPalindromeInString {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("Enter a string:");

String input = sc.nextLine();

sc.close();


String largestPalindrome = findLargestPalindrome(input);

System.out.println("The largest palindrome in the string is: " + largestPalindrome);

}


// Method to find the largest palindrome

private static String findLargestPalindrome(String str) {

String largestPalindrome = "";


for (int i = 0; i < str.length(); i++) {

// Odd-length palindromes

String oddPalindrome = expandAroundCenter(str, i, i);

if (oddPalindrome.length() > largestPalindrome.length()) {

largestPalindrome = oddPalindrome;

}


// Even-length palindromes

String evenPalindrome = expandAroundCenter(str, i, i + 1);

if (evenPalindrome.length() > largestPalindrome.length()) {

largestPalindrome = evenPalindrome;

}

}


return largestPalindrome;

}


// Helper method to expand around center and check for palindrome

private static String expandAroundCenter(String str, int left, int right) {

while (left >= 0 && right < str.length() && str.charAt(left) == str.charAt(right)) {

left--;

right++;

}

return str.substring(left + 1, right);

}

}


40)Fibonacci Series


import java.util.Scanner;

public class NonRecursiveFibonacci {


public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("Enter the number of Fibonacci numbers to generate:");

int n = sc.nextInt();

sc.close();

int firstFibonacci = 1;

int secondFibonacci = 1;

System.out.println(firstFibonacci);

System.out.println(secondFibonacci);

for (int i = 2; i < n; i++) {

int currentFibonacci = firstFibonacci + secondFibonacci;

System.out.println(currentFibonacci);

firstFibonacci = secondFibonacci;

secondFibonacci = currentFibonacci;

}

}

}

41) How to remove Whitespaces from String


//need to add below deppendency in pom.xml file

<dependency>

<groupId>org.apache.commons</groupId>

<artifactId>commons-lang3</artifactId>

<version>3.12.0</version>

</dependency>


import org.apache.commons.lang3.StringUtils

public class RemoveWhitespaces {

public static void main(String[] args) {

// String input = " Hello World ! ";

// String result = StringUtils.deleteWhitespace(input);

// System.out.println("String without whitespaces: \"" + result + "\"");

String input = " Hello world ! ";

String result =StringUtils.deleteWhitespace(input);

System.out.println("String without whitespaces:"+result);

}

}


42) Sorting an array


import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; public class ArraySortUsingIntegerStringListStream{ public static void main(String[] args) { // Integer Array Integer[] arr = {5, 3, 9, 4, 6, 99}; System.out.println("Original Array: " + Arrays.toString(arr)); // Print sorted array using streams System.out.println("Ascending order:"); Arrays.stream(array).forEach(e -> System.out.print(e + " "));


// With Array.sort(): Arrays.sort(array);


// Ascending using Stream List<Integer> ascSorted = Arrays.stream(arr) .sorted() .collect(Collectors.toList()); System.out.println("Sorted (Ascending): " + ascSorted); // Descending using Stream List<Integer> descSorted = Arrays.stream(arr) .sorted(Comparator.reverseOrder()) .collect(Collectors.toList()); System.out.println("Sorted (Descending): " + descSorted);


// Reverse alphabetical order using streams  
List<String> names = Arrays.asList("chiru", "venky", "nagaruna", "balaiah", "saikumar", "suman");        
        List<String> sorted = names.stream()
.sorted(Comparator.reverseOrder()).collect(Collectors.toList());
        System.out.println(sorted);

// Bubble sort remains as an algorithm example (not stream-based) Integer[] bubble = {5, 3, 9, 4, 6, 99}; for (int i = 0; i < bubble.length - 1; i++) { for (int j = 0; j < bubble.length - i - 1; j++) { if (bubble[j] > bubble[j + 1]) { int temp = bubble[j]; bubble[j] = bubble[j + 1]; bubble[j + 1] = temp; } } } System.out.println("Bubble Sorted: " + Arrays.toString(bubble)); // String Array String[] strArr = {"banana", "apple", "cherry", "date"}; System.out.println("Original String Array: " + Arrays.toString(strArr)); // Alphabetical sort List<String> sortedStrings = Arrays.stream(strArr) .sorted() .collect(Collectors.toList()); System.out.println("Sorted Strings (Alphabetical): " + sortedStrings); // Sort by length List<String> sortedByLength = Arrays.stream(strArr) .sorted(Comparator.comparingInt(String::length)) .collect(Collectors.toList()); System.out.println("Sorted by Length: " + sortedByLength); // List sorting with streams List<Integer> list = new ArrayList<>(Arrays.asList(5, 2, 8, 1, 3)); System.out.println("Original List: " + list); // Sort ascending using streams List<Integer> sortedListAsc = list.stream() .sorted() .collect(Collectors.toList()); System.out.println("List Sorted (Ascending): " + sortedListAsc); // Sort descending using streams List<Integer> sortedListDesc = list.stream() .sorted(Comparator.reverseOrder()) .collect(Collectors.toList()); System.out.println("List Sorted (Descending): " + sortedListDesc); // Custom sort with stream (Even first, then odd) List<Integer> evenFirst = list.stream() .sorted((a, b) -> { if (a % 2 == 0 && b % 2 != 0) return -1; // a is even, b is odd → a comes first if (a % 2 != 0 && b % 2 == 0) return 1; // a is odd, b is even → b comes first return a - b; }) .collect(Collectors.toList()); System.out.println("List Sorted (Even First): " + evenFirst); } }


43) Find factorial of an integer?


public class Factorial {

public static void main(String[] args) {

int number = 5; // Input number

long factorial = 1;


for (int i = 1; i <= number; i++) {

factorial *= i;

}


System.out.println("Factorial of " + number + " is: " + factorial);

}

}

44) Difference between Java8 filter, groupby


The filter and groupBy operations in Java 8 serve different purposes in the Stream API.

1. Filter:


Filter is used to filter the elements from a stream based on a condition (predicate). and it returns only those elements that match the predicate.


Method Signature: Stream<T> filter(Predicate<? super T> predicate);


Use Case: Filter is used to retrieve a subset of elements from a collection or stream.


Example: import java.util.Arrays;

import java.util.List;

import java.util.stream.Collectors;


public class FilterExample {

public static void main(String[] args) {

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);


// Filter even numbers

List<Integer> evenNumbers = numbers.stream()

.filter(num -> num % 2 == 0)

.collect(Collectors.toList());


System.out.println("Even Numbers: " + evenNumbers);

}

}


2. groupBy:


groupBy is used to the group elements of a stream into a Map based on a classifier function.

and it returns a Map<K, List<T>> where K is the key generated by the classifier and List<T> is the list of items sharing the same key


Method: It is not directly part of the Stream API but is achieved using Collectors.groupingBy().


Use case: groupBy is used to categorize elements of a stream based on a specific property.


Example:

import java.util.Arrays;

import java.util.List;

import java.util.Map;

import java.util.stream.Collectors;


public class GroupByExample {

public static void main(String[] args) {

List<String> words = Arrays.asList("apple", "banana", "apricot", "blueberry", "cherry", "avocado");


// Group words by their first letter

Map<Character, List<String>> groupedByFirstLetter = words.stream()

.collect(Collectors.groupingBy(word -> word.charAt(0)));


System.out.println("Grouped Words: " + groupedByFirstLetter);

}

}


Key Differences:

FeatureFilterGroupBy
PurposeFilters elements based on a condition.Groups elements based on a classifier function.
ResultStream or collection with filtered elements.Map with grouped elements.
Return TypeStream<T>Map<K, List<T>>
Example UseGet even numbers from a list.Group words by their starting letter.


45) Java map() and to toMap() Programs


1. map():


map() is used to transform elements in a stream into another form. It operates on each element and produces a new stream with transformed elements.

and it returns a Stream<R>, where R is the transformed type.


Use Case: map() is used to data transformation or mapping from one type to another (e.g., from String to Integer or from lowercase to uppercase).


Example:

import java.util.Arrays;

import java.util.List;

import java.util.stream.Collectors;


public class MapExample {

public static void main(String[] args) {

List<String> names = Arrays.asList("Swamy", "Pranu", "Srihan");


// Convert names to uppercase using map()

List<String> upperCaseNames = names.stream()

.map(String::toUpperCase)

.collect(Collectors.toList());


System.out.println("Uppercase Names: " + upperCaseNames);

}

}


2. toMap():


toMap() is used to collect stream elements into a Map by applying key and value mapping functions.

and it returns a Map<K, U>, where K is the key and U is the value.


Use case: toMap() is used to create mappings (e.g., name to length, product to price).


Example:

import java.util.Arrays;

import java.util.List;

import java.util.Map;

import java.util.stream.Collectors;


public class ToMapExample {

public static void main(String[] args) {

List<String> names = Arrays.asList("Swamy", "Pranu", "Srihan");


// Create a map where key is the name and value is the length of the name

Map<String, Integer> nameLengthMap = names.stream()

.collect(Collectors.toMap(

name -> name, // Key mapper

name -> name.length() // Value mapper

));


System.out.println("Name Length Map: " + nameLengthMap);

}

}


Key Differences:

Featuremap()toMap()
PurposeTransforms elements in a stream.Collects elements into a Map.
ResultProduces a transformed Stream<R>.Produces a Map<K, U> with custom key-value pairs.
Return TypeStream with transformed elements.Map with keys and values derived from the stream.
Use CaseData transformation (e.g., convert to uppercase).Create a mapping (e.g., name to length).


CombinedExample: import java.util.Arrays;

import java.util.List;

import java.util.Map;

import java.util.stream.Collectors;


public class CombinedExample {

public static void main(String[] args) {

List<String> names = Arrays.asList("Swamy", "Pranu", "Srihan");


// Convert names to uppercase and collect them into a map

Map<String, Integer> upperCaseNameLengthMap = names.stream()

.map(String::toUpperCase) // Transform names to uppercase

.collect(Collectors.toMap(

name -> name, // Key mapper

name -> name.length() // Value mapper

));


System.out.println("Uppercase Name Length Map: " + upperCaseNameLengthMap);

}

}


46) Java 8 convert list into map


Converting a List to a Map in Java 8 involves using the Stream API and the Collectors.toMap() method.

The process can vary depending on the requirements, such as defining the keys and values, handling duplicate keys,

and customizing the map's behavior.


1. Basic Conversion

  • Purpose: Convert a list to a map by defining how the keys and values are derived from the list elements.

import java.util.Arrays;

import java.util.List;

import java.util.Map;

import java.util.stream.Collectors;


public class ListToMapBasicExample {

public static void main(String[] args) {

List<String> names = Arrays.asList("Swamy", "Pranu", "Srihan");


// Convert list to map where key is the name and value is the length of the name

Map<String, Integer> nameLengthMap = names.stream()

.collect(Collectors.toMap(

name -> name, // Key mapper

name -> name.length() // Value mapper

));


System.out.println("Name Length Map: " + nameLengthMap);

}

}


2. Handling Duplicate Keys

  • If there are duplicate keys (e.g., two elements that map to the same key), toMap() will throw an IllegalStateException.
  • To handle this, you can provide a merge function to resolve conflicts.

3. Custom Map Implementation

  • By default, toMap() creates a HashMap. You can specify a custom Map implementation, such as TreeMap or LinkedHashMap.

Example

import java.util.Arrays;

import java.util.List;

import java.util.Map;

import java.util.stream.Collectors;

import java.util.TreeMap;


public class ListToMapCustomMap {

public static void main(String[] args) {

List<String> names = Arrays.asList("Swamy", "Pranu", "Srihan");


// Use a TreeMap for sorted keys

Map<String, Integer> nameLengthMap = names.stream()

.collect(Collectors.toMap(

name -> name, // Key mapper

name -> name.length(), // Value mapper

(existing, replacement) -> existing, // Merge function

TreeMap::new // Custom map supplier

));


System.out.println("Name Length Map: " + nameLengthMap);

}

}

4. Complex Object Conversion

  • Convert a list of custom objects into a map by specifying a property for the key and another property (or the object itself) for the value.

Example

import java.util.Arrays;

import java.util.List;

import java.util.Map;

import java.util.stream.Collectors;


class Employee {

private int id;

private String name;


// Constructor

public Employee(int id, String name) {

this.id = id;

this.name = name;

}


// Getters

public int getId() {

return id;

}


public String getName() {

return name;

}


@Override

public String toString() {

return "Employee{id=" + id + ", name='" + name + "'}";

}

}


public class ListToMapComplexExample {

public static void main(String[] args) {

List<Employee> employees = Arrays.asList(

new Employee(1, "Swamy"),

new Employee(2, "Pranu"),

new Employee(3, "Srihan")

);


// Convert list to map where key is employee ID and value is the employee object

Map<Integer, Employee> employeeMap = employees.stream()

.collect(Collectors.toMap(

Employee::getId, // Key mapper

employee -> employee // Value mapper

));


System.out.println("Employee Map: " + employeeMap);

}

}

47) Functional interface in java 8


In Java, a functional interface is an interface that contains exactly one abstract method.

Functional interfaces can have any number of default and static methods, but only one abstract method.

They are primarily used as the target for lambda expressions and method references, enabling functional programming in Java.


Key Points About Functional Interfaces

  1. Marked with the @FunctionalInterface annotation (optional but recommended to indicate intent).
  2. Can contain default and static methods.
  3. Used with lambda expressions for concise code.

The java.util.function package provides several built-in functional interfaces, such as Predicate, Consumer, Supplier, etc.

Example: Custom Functional Interface

@FunctionalInterface interface MyFunctionalInterface { void displayMessage(String message); // Single abstract method }

public class FunctionalInterfaceExample { public static void main(String[] args) { // Implementing the functional interface using a lambda expression MyFunctionalInterface messagePrinter = (message) -> { System.out.println("Message: " + message); }; // Using the implemented method messagePrinter.displayMessage("Hello, Functional Interface!"); } }

Example: Using Built-in Functional Interface (Predicate)

The Predicate<T> functional interface takes a single input and returns a boolean result.

import java.util.function.Predicate; public class PredicateExample { public static void main(String[] args) { // Predicate to check if a number is greater than 10 Predicate<Integer> isGreaterThanTen = (num) -> num > 10; // Test the predicate System.out.println(isGreaterThanTen.test(15)); // Output: true System.out.println(isGreaterThanTen.test(8)); // Output: false } }

48) Lambda Expressions in Java 8

A lambda expression is a concise way to represent an anonymous function in Java.
It simplifies the implementation of functional interfaces, making the code more readable and concise.

Syntax of a Lambda Expression:

(parameters) -> expression (parameters) -> { statements; }

Key Points:

lambda expression is used to implement functional interfaces (interfaces with a single abstract method).
And it eliminates the need for anonymous inner classes.

Example 1: Basic Lambda Expression

@FunctionalInterface interface Greeting { void sayHello(String name); } public class LambdaExample { public static void main(String[] args) { // Using a lambda expression to implement the functional interface Greeting greet = (name) -> System.out.println("Hello, " + name + "!"); greet.sayHello("Alice"); } }

Example 2: Using Lambda Expression with Runnable

public class LambdaRunnableExample { public static void main(String[] args) { // Without lambda: Anonymous inner class Thread thread1 = new Thread(new Runnable() { @Override public void run() { System.out.println("Thread 1 is running"); } }); thread1.start(); // With lambda expression Thread thread2 = new Thread(() -> System.out.println("Thread 2 is running")); thread2.start(); } }

Example 3: Using Lambda with a Built-in Functional Interface (Consumer)

The Consumer<T> functional interface takes an input and performs some action, without returning a result.

import java.util.function.Consumer; public class LambdaConsumerExample { public static void main(String[] args) { Consumer<String> printMessage = message -> System.out.println("Message: " + message); // Using the lambda expression printMessage.accept("Lambda Expressions are powerful!"); } }

Example 4: Using Lambda with Streams

import java.util.Arrays; import java.util.List; public class LambdaStreamExample { public static void main(String[] args) { List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); // Using a lambda expression with forEach numbers.forEach(number -> System.out.println(number * 2)); } }


Benefits of Lambda Expressions

  1. Conciseness: Reduces boilerplate code.
  2. Readability: Simplifies the implementation of single-method interfaces.
  3. Improved Efficiency: Especially with collections and streams, lambda expressions make code easier to write and maintain.

49) Method References in Java 8

Method references are a shorthand notation of a lambda expression that executes a specific method.
They improve readability by directly referencing existing methods instead of defining a lambda that calls the method.

Types of Method References:
  • Static Method Reference: ClassName::staticMethodName
  • Instance Method Reference: instance::instanceMethodName
  • Reference to an Instance Method of an Arbitrary Object: ClassName::instanceMethodName
  • Constructor Reference: ClassName::new
  • Examples of Method References

    Example 1: Static Method Reference:

    import java.util.function.Consumer; public class StaticMethodReferenceExample { public static void printMessage(String message) { System.out.println("Static Method: " + message); } public static void main(String[] args) { Consumer<String> consumer = StaticMethodReferenceExample::printMessage; consumer.accept("Hello from static method!"); } }

    Example 2: Instance Method Reference:
    import java.util.function.Consumer; public class InstanceMethodReferenceExample { public void showMessage(String message) { System.out.println("Instance Method: " + message); } public static void main(String[] args) { InstanceMethodReferenceExample example = new InstanceMethodReferenceExample(); // Reference to an instance method of a particular object Consumer<String> consumer = example::showMessage; consumer.accept("Hello from instance method!"); } }

    Example 3: Reference to an Instance Method of an Arbitrary Object

    import java.util.Arrays; import java.util.List; public class ArbitraryObjectMethodReference { public static void main(String[] args) { List<String> names = Arrays.asList("Alice", "Bob", "Charlie"); // Reference to the instance method 'toUpperCase' of String class names.stream() .map(String::toUpperCase) .forEach(System.out::println); } }

    Example 4: Constructor Reference

    import java.util.function.Supplier; class Person { private String name; public Person() { this.name = "Default Name"; } public String getName() { return name; } } public class ConstructorReferenceExample { public static void main(String[] args) { // Constructor reference Supplier<Person> personSupplier = Person::new; // Creating a new Person instance Person person = personSupplier.get(); System.out.println("Person Name: " + person.getName()); } }

    Benefits of Method References

    1. Improves Readability: More concise than lambda expressions.
    2. Reusable Code: Directly we can pass references in existing methods.
    3. Integration with Functional Interfaces: Works seamlessly with Java's built-in functional interfaces.

    Use Cases

    • Simplifying lambda expressions when the method already exists.
    • Processing collections using Streams API.
    • Implementing functional interfaces in a clean and readable way.
    50) Internal working of Hash Map, Hashset, concurrent hashmap.

    1. HashMap

    A HashMap is a collection that stores data in key-value pairs and provides

    constant-time performance (O(1)) for basic operations like insert, delete, and lookup, assuming the hash function

    disperses elements properly among the buckets.

    Internal Structure of HashMap:

    1.Hashing Mechanism:

    a)HashMap uses a hash function to map keys to an index (bucket) in an internal array called a bucket array.

    b)Each bucket stores a linked list (or tree in case of high collision) of Node objects containing the key, value, hash, and a reference to the next node.

    2.Node Structure:

    static class Node<K, V> { final int hash; final K key; V value; Node<K, V> next; }

    3.Collision Handling:

    Hash collisions are handled using chaining. Multiple keys with the same hash index

    are stored in a linked list or binary tree.

    4.Load Factor and Rehashing:

    • Load factor (default: 0.75) determines when the HashMap should resize.
    • When the number of elements exceeds capacity * load factor, the HashMap doubles its size and rehashes all elements.
    import java.util.HashMap; public class HashMapExample { public static void main(String[] args) { HashMap<String, Integer> map = new HashMap<>(); map.put("Alice", 30); map.put("Bob", 25); map.put("Charlie", 35); System.out.println(map.get("Alice")); // Output: 30 } }

    2. HashSet

    A HashSet is a collection that uses a HashMap internally to store elements. It allows no duplicates

    and provides constant-time performance (O(1)) for basic operations like add, remove, and contains.

    Internal Structure of HashSet:

    a)HashSet uses a HashMap to store elements.

    b)Each element in the HashSet is stored as a key in the HashMap, with a constant dummy value (PRESENT).

    import java.util.HashSet; public class HashSetExample { public static void main(String[] args) { HashSet<String> set = new HashSet<>(); set.add("Apple"); set.add("Banana"); set.add("Apple"); // Duplicate, won't be added System.out.println(set); // Output: [Apple, Banana] } }

    3. ConcurrentHashMap

    A ConcurrentHashMap is a thread-safe version of a HashMap that allows multiple threads

    to access it concurrently without compromising performance.

    Internal Structure of ConcurrentHashMap:

    a)Segmentation:

    i)Before Java 8: Used a segmented locking mechanism (separate locks for different buckets).

    ii)From Java 8: Replaced segmentation with a bucket-level locking mechanism and improved performance

    using a ConcurrentLinkedQueue or binary trees for collision handling.

    b)Thread Safety:

    i)Multiple threads can operate on different buckets concurrently.

    ii)Locks are applied at the bucket level, not the entire map.

    c)No Null Values:

    ConcurrentHashMap does not allow null keys or null values to avoid ambiguity during concurrent access.

    Example:

    import java.util.concurrent.ConcurrentHashMap; public class ConcurrentHashMapExample { public static void main(String[] args) { ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>(); map.put("John", 50); map.put("Jane", 60); // Accessing elements concurrently System.out.println(map.get("John")); // Output: 50 } }

    Comparison Table

    FeatureHashMapHashSetConcurrentHashMap
    Thread SafetyNot thread-safeNot thread-safeThread-safe
    Null Keys/Values1 null key, many null valuesAllows null elementsDoes not allow null keys or values
    PerformanceFast (single thread)Fast (single thread)Good (multithreaded access)
    Collision HandlingLinked List / TreeSame as HashMapConcurrent buckets

    51) Difference Between HashMap and ConcurrentHashMap

    FeatureHashMapConcurrentHashMap
    Thread SafetyNot thread-safe.Thread-safe, supports concurrent access.
    Null Keys/ValuesAllows one null key and multiple null values.Does not allow null keys or null values.
    ConcurrencyFails under concurrent modifications without external synchronization.Optimized for multi-threaded environments using bucket-level locking.
    Locking MechanismNo locking; requires explicit synchronization for thread safety.Uses bucket-level locking for better concurrency.
    PerformanceFast for single-threaded applications.Performs well under multi-threaded scenarios.
    IterationMay throw a ConcurrentModificationException during concurrent modifications.No ConcurrentModificationException during iteration.
    Read and Write OperationsReads and writes are not atomic.Reads are lock-free; writes lock buckets instead of the whole map.
    Use CaseSuitable for single-threaded or low-concurrency applications.Suitable for high-concurrency applications.


    HashMap Example (Not Thread-Safe):

    import java.util.HashMap; public class HashMapExample { public static void main(String[] args) { HashMap<String, Integer> map = new HashMap<>(); map.put("Swamy", 25); map.put("Srihan", 30); // Single-threaded access System.out.println("Swamy's age: " + map.get("Swamy")); // Output: 25 // Multi-threaded access (may cause issues) Thread writer = new Thread(() -> map.put("Raju", 35)); Thread reader = new Thread(() -> System.out.println("Raju's age: " + map.get("Raju"))); writer.start(); reader.start(); } }

    Potential Issues with HashMap in Multi-threaded Scenarios:

    1. Data Corruption: Simultaneous writes may lead to inconsistent state.
    2. ConcurrentModificationException: Iteration during modification may fail.

    ConcurrentHashMap Example (Thread-Safe):

    import java.util.concurrent.ConcurrentHashMap; public class ConcurrentHashMapExample { public static void main(String[] args) { ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>(); map.put("Swamy", 25); map.put("Srihan", 30); // Multi-threaded access Thread writer = new Thread(() -> map.put("Raju", 35)); Thread reader = new Thread(() -> System.out.println("Raju's age: " + map.get("Raju"))); writer.start(); reader.start(); // Concurrent iteration map.forEach((key, value) -> System.out.println(key + ": " + value)); } }

    Features of ConcurrentHashMap:

    1. Thread Safety: Operations like put(), get(), and remove() are thread-safe.
    2. Fine-Grained Locking: Only the bucket being modified is locked, allowing other threads to access different buckets.
    3. No Blocking for Reads: Read operations do not block even if writes are occurring on other buckets.

    Key Points

    1. Use HashMap when thread-safety is not required, and the application is single-threaded or has minimal concurrency.
    2. Use ConcurrentHashMap in multi-threaded environments to avoid data corruption and improve performance with concurrent access.
    52) Difference between SynchronizedMap and ConcurrentHashMap

    Difference Between SynchronizedMap and ConcurrentHashMap

    FeatureSynchronizedMap (via Collections.synchronizedMap)ConcurrentHashMap
    Thread SafetyThread-safe using a single lock on the entire map.Thread-safe using bucket-level locking (lock striping).
    Locking MechanismEntire map is locked during all operations, including reads and writes.Locks individual buckets, allowing higher concurrency.
    Concurrency LevelOnly one thread can access the map at a time.Multiple threads can operate on different buckets simultaneously.
    PerformanceSlower due to single lock for the entire map.Faster due to fine-grained locking.
    IterationMust explicitly synchronize during iteration to avoid ConcurrentModificationException.No explicit synchronization required during iteration.
    Null Keys/ValuesAllows one null key and multiple null values.Does not allow null keys or null values.
    Use CaseSuitable for applications with low concurrency requirements.Ideal for high-concurrency applications.

    SynchronizedMap Example:

    import java.util.Collections; import java.util.HashMap; import java.util.Map; public class SynchronizedMapExample { public static void main(String[] args) { Map<String, Integer> synchronizedMap = Collections.synchronizedMap(new HashMap<>()); // Adding data synchronizedMap.put("Swamy", 25); synchronizedMap.put("Srihan", 30); // Multi-threaded access Thread writer = new Thread(() -> synchronizedMap.put("Raju", 35)); Thread reader = new Thread(() -> System.out.println(synchronizedMap.get("Raju"))); writer.start(); reader.start(); // Iterating (explicit synchronization required) synchronized (synchronizedMap) { synchronizedMap.forEach((key, value) -> System.out.println(key + ": " + value)); } } }

    Key Notes:

    1. Must explicitly synchronize the map during iteration.
    2. A single lock reduces throughput in multi-threaded environments.
    ConcurrentHashMap Example:

    import java.util.concurrent.ConcurrentHashMap; public class ConcurrentHashMapExample { public static void main(String[] args) { ConcurrentHashMap<String, Integer> concurrentMap = new ConcurrentHashMap<>(); // Adding data concurrentMap.put("Swamy", 25); concurrentMap.put("Srihan", 30); // Multi-threaded access Thread writer = new Thread(() -> concurrentMap.put("Raju", 35)); Thread reader = new Thread(() -> System.out.println(concurrentMap.get("Raju"))); writer.start(); reader.start(); // Iterating (no explicit synchronization required) concurrentMap.forEach((key, value) -> System.out.println(key + ": " + value)); } }

    Key Features:

    1. No need for explicit synchronization during iteration.
    2. Supports higher concurrency with bucket-level locking.

    When to Use

    1. SynchronizedMap:

      • Use when the application is single-threaded or has low concurrency.
      • Preferable when minimal synchronization overhead is acceptable.
    2. ConcurrentHashMap:

      • Use in high-concurrency applications to ensure better performance.
      • Ideal when frequent reads and writes are required.

    53) RemoveDuplicates from array

    import java.util.Arrays;
    import java.util.stream.IntStream;

    public class RemoveDuplicatesNumbers {
        public static void main(String[] args) {
            int[] array = {10, 20, 30, 10, 10, 50};

            // Remove duplicates using Stream
            int[] result = IntStream.of(array)
                                    .distinct()
                                    .toArray();

            // Output results
            System.out.println("Size after deletion: " + result.length);
            System.out.println("Elements: " + Arrays.toString(result));
        }
    }

    Explanation:

    • IntStream.of(array) → Converts array to stream.

    • .distinct() → Filters out duplicate integers.

    • .toArray() → Converts the stream back to an array.

    java

    int[] array = {10, 20, 30, 10, 10, 50}; int[] unique = Arrays.stream(array).distinct().toArray(); System.out.println("Size: " + unique.length); System.out.println("Elements: " + Arrays.toString(unique));

    55) Count Character With Given String Using Streams

    public class CountCharacterWithGivenString
    { public static void main(String[] args) { String str = "InfosysLimited"; char c1 = 'e'; char c2 = 's'; System.out.println(countChar(str, c1)); System.out.println(countChar(str, c2)); } public static long countChar(String str, char ch) { return str.chars() // IntStream of char values .filter(c -> c == ch) // filter matching char .count(); // count occurrences } }

    ๐Ÿ” Explanation:

    str.chars() → Converts the string to an IntStream of Unicode values. .filter(c -> c == ch) → Filters characters matching the target. .count() → Returns the number of times the character appears.

    56) Write a program for First Non-Repeating Character

    import java.util.LinkedHashMap;

    import java.util.Map;

    import java.util.Optional;

    import java.util.function.Function;

    import java.util.stream.Collectors;


    public class FirstNonRepeatingChar {

    public static void main(String[] args) {

    String input = "InfosysLimited";

    Optional<Character> result = findFirstNonRepeatingChar(input);


    if (result.isPresent()) {

    System.out.println("First non-repeating character is: " + result.get());

    } else {

    System.out.println("All characters are repeating or string is empty.");

    }

    }


    public static Optional<Character> findFirstNonRepeatingChar(String str) {

    return str.chars()

    .mapToObj(c -> (char) c)

    .collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()))

    .entrySet()

    .stream()

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

    .map(Map.Entry::getKey)

    .findFirst();

    }

    }

    ๐Ÿ” Explanation: str.chars() → converts string to an IntStream. .mapToObj(c -> (char) c) → converts each int to Character. groupingBy(..., LinkedHashMap::new, ...) → preserves insertion order. Collectors.counting() → counts frequency of each character. .filter(e -> e.getValue() == 1) → filters non-repeating ones. .findFirst() → returns the first one. ๐Ÿ“ Sample Output: For input "InfosysLimited", the output will be: First non-repeating character is: I


    57) Write a program to list of unique odd numbers from a nested list List<List<Integer>> nums = List.of(List.of(1,2,3,4), List.of(1,3,4), List.of(5,7,9));


    To extract a list of unique odd numbers from your nested list nums,
    you can use Java Streams with flatMap, filter, and distinct:

    import java.util.List; import java.util.stream.Collectors; public class UniqueOddNumbersOrStringFromNestedList { public static void main(String[] args) { List<List<Integer>> nums = List.of( List.of(1, 2, 3, 4), List.of(1, 3, 4), List.of(5, 7, 9) ); List<Integer> uniqueOddNumbers = nums.stream() .flatMap(List::stream) // Flatten the nested list .filter(n -> n % 2 != 0) // Keep only odd numbers .distinct() // Remove duplicates .collect(Collectors.toList()); // Collect to a list System.out.println(uniqueOddNumbers); // Output: [1, 3, 5, 7, 9]

    Example2: List<List<String>> nested = Arrays.asList( Arrays.asList("A", "B"), Arrays.asList("C", "D") );
    Stream<String> flat = nested.stream() .flatMap(List::stream);
    .forEach(System.out::println); } }

    11) String s ="race car";
    reverse program using lambda simple program

    import java.util.stream.Collectors; public class ReverseStringUsingStreamOrIntStream { public static void main(String[] args) { String s = "race car"; //1)Using StringBuilder String reversed = new StringBuilder(s) .reverse() .toString();

    //2)Simpler Lambda with Streams (Simple process)
    String reversed = IntStream.rangeClosed(1, s.length()) .mapToObj(i -> s.charAt(s.length() - i))
    .map(String::valueOf) .collect(Collectors.joining());

    //3)Using Arrays.stream
    String reversed3 = Arrays.stream(s.split("")).collect(Collectors.collectingAndThen(Collectors.toList(), lst -> { Collections.reverse(lst); return String.join("", lst); }));

    //4)Lambda with Streams (Best approach)
    String reversed = s.chars() .mapToObj(c -> (char) c) .collect(Collectors.collectingAndThen( Collectors.toList(), list -> { Collections.reverse(list); return list.stream() .map(String::valueOf) .collect(Collectors.joining()); }));
    System.out.println("Original : " + s); System.out.println("Reversed : " + reversed); } }

    15)Sample program for TreeSetSort
    import java.util.TreeSet;
    import java.util.Set;

    public class TreeSetSort {
        public static void main(String[] args) {
            Set<Integer> set = new TreeSet<>(Comparator.reverseOrder());
            Collections.addAll(set, 10, 5, 15, 20, 0);
            System.out.println("Descending TreeSet: " + set); // Output: [20, 15, 10, 5, 0]
        }
    }
    Option 3: Full Lambda With Comparator Chaining (if sorting objects)
    TreeSet<Employee> sortedByName = new TreeSet<>(
        Comparator.comparing(Employee::getName)
                  .thenComparing(Employee::getId)
    );

    16)Sample program for ReverseOrderStreams
    import java.util.*;
    import java.util.stream.Collectors;

    public class ReverseOrderUsingList {
        public static void main(String[] args) {
            // 1️⃣ Reverse order for String list
            List<String> names = Arrays.asList("chiru", "venky", "nagaruna", "balaiah", "saikumar", "suman");
            List<String> reversedNames = names.stream()
                                              .sorted(Comparator.reverseOrder())
                                              .collect(Collectors.toList());
            System.out.println("Names in reverse alphabetical order: " + reversedNames);

            // 2️⃣ Reverse order for Integer list
            List<Integer> list = Arrays.asList(5, 2, 8, 1, 3);
            List<Integer> reversedNumbers = list.stream()
                                                .sorted(Comparator.reverseOrder())
                                                .collect(Collectors.toList());
            System.out.println("Numbers in descending order: " + reversedNumbers);
        }
    }race car

    25: Write the program for reverses the order of words
          String str= this is a string
          Output: string a is this

    Example with Collections.reverse(), String.join():

    import java.util.Collections;

    import java.util.List;

    import java.util.Arrays;


    class ReverseOrderOfWords1 {

    public static void main(String[] args) {

    String input = "this is a string";

    List<String> words = Arrays.asList(input.split(" "));

    Collections.reverse(words);

    String result = String.join(" ", words);

    System.out.println(result);

    }

    }


    Example with StringBuilder:

    class ReverseOrderOfWords2 {

    public static void main(String[] args) {

    String input = "this is a string";

    String[] words = input.split(" ");

    StringBuilder result = new StringBuilder();


    for (int i = words.length - 1; i >= 0; i--) {

    result.append(words[i]).append(" ");

    }


    System.out.println(result.toString().trim());

    }



    26: Write a program to find unique value between two arrays
             originalarr={1, 2,3,4,5,6,7,8,9}
            Duparray={1,2,3,4,5,7,8,9}

    Example with Streams:

    import java.util.Arrays;

    import java.util.Set;

    import java.util.stream.Collectors;


    public class UniqueValuesFromArrays {

    public static void main(String[] args) {

    int[] originalArr = {1, 2, 3, 4, 5, 6, 7, 8, 9};

    int[] dupArray = {1, 2, 3, 4, 5, 7, 8, 9};


    Set<Integer> dupSet = Arrays.stream(dupArray)

    .boxed() //converts int to Integer

    .collect(Collectors.toSet()); //creates a set of values from dupArray for fast contains() lookup.


    int uniqueValue = Arrays.stream(originalArr)

    .filter(num -> !dupSet.contains(num))

    .findFirst()

    .orElseThrow(() -> new RuntimeException("No unique value found"));


    System.out.println("Unique value: " + uniqueValue);

    }

    }

    58)Reverse Vowels of a String Input: "hello" → Output: "holle"
    Input: "leetcode" → Output: "leotcede"

    public class ReverseVowelsIntheString {

    public static String reverseVowels(String s) {

    Set<Character> vowels = Set.of('a','e','i','o','u','A','E','I','O','U');

    char[] arr = s.toCharArray();

    int left = 0, right = arr.length - 1;


    while (left < right) {

    while (left < right && !vowels.contains(arr[left])) left++;

    while (left < right && !vowels.contains(arr[right])) right--;


    char temp = arr[left];

    arr[left] = arr[right];

    arr[right] = temp;

    // Move both pointers inward

    left++;

    right--;

    }

    return new String(arr);

    }


    public static void main(String[] args) {

    System.out.println(reverseVowels("hello")); // holle

    System.out.println(reverseVowels("leetcode")); // leotcede

    }

    }


    59)2. Rotated Sorted Array - Search with O(log n)
    ๐Ÿ”น Problem:
    Given a rotated sorted array, search for a target in O(log n) time.
    Input: [4,5,6,7,0,1,2], target = 0 → Output: 4

    public class RotatedArraySearch {

    public static int search(int[] nums, int target) {

    int low = 0, high = nums.length - 1;

    while (low <= high) {

    int mid = (low + high) / 2;


    if (nums[mid] == target) return mid;


    if (nums[low] <= nums[mid]) { // left half sorted

    if (nums[low] <= target && target < nums[mid])

    high = mid - 1;

    else

    low = mid + 1;

    } else { // right half sorted

    if (nums[mid] < target && target <= nums[high])

    low = mid + 1;

    else

    high = mid - 1;

    }

    }

    return -1;

    }

    public static void main(String[] args) {

    int[] nums = {4, 5, 6, 7, 0, 1, 2};

    int target = 0;

    int index = search(nums, target);


    if (index != -1)

    System.out.println("Target " + target + " found at index: " + index);

    else

    System.out.println("Target not found.");

    }

    }


    60).Pothole Repair Cost
    ๐Ÿ”น Problem:
    Each '.' is a
    pothole, '#' is smooth road. Cost for repairing n potholes = n + 1. Calculate total cost.
    * */

    public class PotholeCost {

    public static int calculate(String road) {

    int totalCost = 0, count = 0;

    for (char c : road.toCharArray()) {

    if (c == '.') {

    count++;

    } else if (count > 0) {

    totalCost += count + 1;

    count = 0;

    }

    }

    if (count > 0)

    totalCost += count + 1;

    if (road.charAt(road.length() - 1) == '.') return totalCost-1; // Return -1 if last char is '.'

    return totalCost;

    }


    public static void main(String[] args) {

    System.out.println(calculate("..#..#.")); // Output: 7

    }

    }


    61).4. Sort 0s, 1s, 2s in O(n)
    ๐Ÿ”น Problem:
    Given array with 0s, 1s, and 2s, sort them in O(n) time.
    */


    public class SortColors {

    public static void sort(int[] arr) {

    int low = 0, mid = 0, high = arr.length - 1;


    while (mid <= high) {

    if (arr[mid] == 0) {

    int temp = arr[low];

    arr[low++] = arr[mid];

    arr[mid++] = temp;

    } else if (arr[mid] == 1) {

    mid++;

    } else {

    int temp = arr[mid];

    arr[mid] = arr[high];

    arr[high--] = temp;

    }

    }

    }


    public static void main(String[] args) {

    int[] arr = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 1};

    sort(arr);

    System.out.println(Arrays.toString(arr));

    }

    }

    62)You're trying to group anagrams —

    i.e., words that contain the same characters but in different orders — into sublists. For example:

    input is: String[] arr = { "abc", "cab", "tab", "acb", "abt" };

    output is: [[tab, abt], [abc, cab, acb]]

    import java.util.Arrays;

    import java.util.List;

    import java.util.stream.Collectors;


    public class Anagrams_Group {

    public static void main(String[] args) {

    String[] arr = { "abc", "cab", "tab", "acb", "abt" };

    List<List<String>> groupedAnagrams = Arrays.stream(arr).collect(Collectors.groupingBy(word -> {

    // Sort the characters in each word to create the key

    char[] chars = word.toCharArray();

    Arrays.sort(chars);

    return new String(chars);

    })).values().stream().collect(Collectors.toList());


    System.out.println(groupedAnagrams);

    }

    }


    No comments:

    Post a Comment