Friday, 5 April 2013

Important Collections interview Questions


1)calculate the average salary of male employees using Java Streams.

Employee is having empName,gender,salary.

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

  • We have to create Employee POJO class.
  • Then we have use stream with filter and mapToDouble followed by average().
@Data public class Employee { private final String empName; private final String gender; private final double salary; }

import java.util.Arrays; import java.util.List; public class Main { public static void main(String[] args) {
//Used var and List.of() (Java 10+).
var employees = List.of( new Employee("John", "Male", 50000), new Employee("Alice", "Female", 60000), new Employee("Bob", "Male", 55000), new Employee("Diana", "Female", 65000) );
//If we use (Java 8). List<Employee> employees = Arrays.asList( new Employee("John", "Male", 50000), new Employee("Alice", "Female", 60000), new Employee("Bob", "Male", 55000), new Employee("Diana", "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); } }
To save employee data into a CSV file in the format John,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,%.2f", 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.

2)Spring Boot REST Controller for full CRUD operations (getAllEmployees, saveEmployee, updateEmployee, deleteEmployee) using MS SQL Server and Spring Data JPA

1. Employee.java – Entity Class
package com.example.demo.entity; import jakarta.persistence.*; import lombok.*; @Entity @Table(name = "employees") @Data @NoArgsConstructor @AllArgsConstructor public class Employee { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String empName; private String gender; private double salary; }

✅ 2. EmployeeRepository.java

package com.example.demo.repository; import com.example.demo.entity.Employee; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface EmployeeRepository extends JpaRepository<Employee, Long> { }

✅ 3. EmployeeService.java

package com.example.demo.service; import com.example.demo.entity.Employee; import com.example.demo.repository.EmployeeRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service public class EmployeeService { @Autowired private EmployeeRepository repository; public List<Employee> getAllEmployees() { return repository.findAll(); } public Employee saveEmployee(Employee employee) { return repository.save(employee); } public Employee updateEmployee(Long id, Employee updatedEmployee) { Optional<Employee> optionalEmp = repository.findById(id); if (optionalEmp.isPresent()) { Employee emp = optionalEmp.get(); emp.setEmpName(updatedEmployee.getEmpName()); emp.setGender(updatedEmployee.getGender()); emp.setSalary(updatedEmployee.getSalary()); return repository.save(emp); } else { throw new RuntimeException("Employee not found with id: " + id); } } public void deleteEmployee(Long id) { repository.deleteById(id); } }

✅ 4. EmployeeController.java

package com.example.demo.controller; import com.example.demo.entity.Employee; import com.example.demo.service.EmployeeService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("/api/employees") public class EmployeeController { @Autowired private EmployeeService service; // GET all employees @GetMapping public ResponseEntity<List<Employee>> getAllEmployees() { return ResponseEntity.ok(service.getAllEmployees()); } // POST save a new employee @PostMapping public ResponseEntity<Employee> saveEmployee(@RequestBody Employee employee) { return ResponseEntity.ok(service.saveEmployee(employee)); } // PUT update an existing employee @PutMapping("/{id}") public ResponseEntity<Employee> updateEmployee(@PathVariable Long id, @RequestBody Employee employee) { return ResponseEntity.ok(service.updateEmployee(id, employee)); } // DELETE an employee @DeleteMapping("/{id}") public ResponseEntity<Void> deleteEmployee(@PathVariable Long id) { service.deleteEmployee(id); return ResponseEntity.noContent().build(); } }

✅ 5. Test EmployeeService with Mockito

๐Ÿ“„ EmployeeServiceTest.java

package com.example.demo.service; import com.example.demo.entity.Employee; import com.example.demo.repository.EmployeeRepository; import org.junit.jupiter.api.*; import org.mockito.*; import java.util.*; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; class EmployeeServiceTest { @Mock private EmployeeRepository repository; @InjectMocks private EmployeeService service; private Employee sampleEmployee; @BeforeEach void setUp() { MockitoAnnotations.openMocks(this); sampleEmployee = new Employee("1", "John", "Male", 50000); } @Test void testGetAllEmployees() { when(repository.findAll()).thenReturn(List.of(sampleEmployee)); List<Employee> employees = service.getAllEmployees(); assertEquals(1, employees.size()); assertEquals("John", employees.get(0).getEmpName()); } @Test void testSaveEmployee() { when(repository.save(sampleEmployee)).thenReturn(sampleEmployee); Employee saved = service.saveEmployee(sampleEmployee); assertNotNull(saved); assertEquals("John", saved.getEmpName()); } @Test void testUpdateEmployee() { when(repository.findById("1")).thenReturn(Optional.of(sampleEmployee)); when(repository.save(any(Employee.class))).thenReturn(sampleEmployee); Employee updated = new Employee("1", "John Updated", "Male", 60000); Employee result = service.updateEmployee("1", updated); assertEquals("John Updated", result.getEmpName()); } @Test void testDeleteEmployee() { service.deleteEmployee("1"); verify(repository, times(1)).deleteById("1"); } }

3)Spring Boot REST Controller for full CRUD operations (getAllEmployeessaveEmployeeupdateEmployeedeleteEmployee) using Mongo DB

✅ 1. Employee.java – MongoDB Document


package com.example.demo.entity; import lombok.*; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; @Data @NoArgsConstructor @AllArgsConstructor @Document(collection = "employees") public class Employee { @Id private String id; private String empName; private String gender; private double salary; }

✅ 2. EmployeeRepository.java


package com.example.demo.repository; import com.example.demo.entity.Employee; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.stereotype.Repository; @Repository public interface EmployeeRepository extends MongoRepository<Employee, String> { }
3)EmployeeService.java & 4)EmployeeController.java  & 5)EmployeeServiceTest.java  same as above

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

package collections;


import java.util.HashMap;

import java.util.Iterator;

import java.util.Map;

import java.util.Set;


class Hashkeyvalue {


// Scenario 1:

public static void main(String[] args) { Map<Integer, String> h = Map.of(10, "swamy", 20, "narayan", 30, "raj"); System.out.println(h); h.forEach((key, value) -> System.out.println(key + "....." + value)); }


// Scenario 2:

public static void main(String[] args) {

Map<Integer, String> h = new HashMap<>();

h.put(10, "swamy");

h.put(20, "narayan");

h.put(30, "raj");

System.out.println(h);


// Scenario 2

Set<Map.Entry<Integer, String>> s = h.entrySet();

Iterator<Map.Entry<Integer, String>> itr = s.iterator();

while (itr.hasNext()) {

Map.Entry<Integer, String> m1 = itr.next();

System.out.println(m1.getKey() + "....." + m1.getValue());

}


// Scenario 3, we concise the code like below

for (Map.Entry<Integer, String> entry : h.entrySet()) {

System.out.println(entry.getKey() + "....." + entry.getValue());

}

}

}

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


5) 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

6) 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));
    }
}

7)stream() Internal Mechanism in Java

๐Ÿง  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> stream = list.stream();

Internally, the above line actually invokes:

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

๐Ÿ” Step-by-Step Internal Flow of stream()


✅ 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.

8) 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

9)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 { Animal getAnimal() { System.out.println("Animal"); return new Animal(); } }

๐Ÿ”น Child Class with Covariant Return

class Dog extends Animal { @Override Dog getAnimal() { // Return type changed from Animal to Dog System.out.println("Dog"); return new Dog(); } }

✅ Output:

Animal a = new Dog(); a.getAnimal(); // Prints: Dog
  • Dog overrides getAnimal() and 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.
10) 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

11)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
==================================================================
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

class Hashvalue {
    //Scenario 1

public static void main(String[] args) {

Map<Integer, String> h = Map.of(10, "swamy", 20, "narayan", 15, "raj");

h.values().forEach(System.out::println);

}


//Scenario 2:

    public static void main(String[] args) {
        Map<Integer, String> h = new HashMap<>();
        h.put(10, "swamy");
        h.put(20, "narayan");
        h.put(15, "raj");
        System.out.println(h);

        Collection<String> c = h.values();
        for (String value : c) {
            System.out.println(value);
        }
    }
}

========================================================================
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

class Hashkey {

   //Scenario 1:
         public static void main(String[] args) {

Map<Integer, String> h = Map.of(10, "swamy", 20, "narayan", 15, "raj");

h.keySet().forEach(System.out::println);

}


   //Scenario 2:
    public static void main(String[] args) {
        Map<Integer, String> h = new HashMap<>();
        h.put(10, "swamy");
        h.put(20, "narayan");
        h.put(15, "raj");
        System.out.println(h);

        Set<Integer> s = h.keySet();
        for (Integer key : s) {
            System.out.println(key);
        }
    }
}

========================================================================
import java.util.Comparator;
import java.util.TreeSet;

class OwnCustmizesort {
    public static void main(String[] args) {
        // Use generics to specify the type as Integer
        TreeSet<Integer> t = new TreeSet<>(new MyComparator());
        t.add(10);
        t.add(5);
        t.add(15);
        t.add(20);
        t.add(0);
        System.out.println(t);
    }
}

// Implement Comparator with generics
class MyComparator implements Comparator<Integer> {
    public int compare(Integer I1, Integer I2) {
        if (I1 < I2)
            return +1;
        else if (I1 > I2)
            return -1;
        else
            return 0;
    }
}

=======Using java 8
import java.util.Comparator;
import java.util.TreeSet;
import java.util.Set;

public class OwnCustomSort {
    public static void main(String[] args) {
        // Using a lambda expression for the comparator
        Set<Integer> t = new TreeSet<>((I1, I2) -> {
            if (I1 < I2)
                return 1;
            else if (I1 > I2)
                return -1;
            else
                return 0;
        });

        // Adding elements to the TreeSet
        t.add(10);
        t.add(5);
        t.add(15);
        t.add(20);
        t.add(0);

        // Printing the TreeSet
        System.out.println(t);
    }
}
================================================================
import java.util.Comparator;
import java.util.TreeSet;

class ReverseAlpha {
//Scenario 1
public static void main(String[] args) {
Set<String> t = new TreeSet<>((s1, s2) ->     s2.compareTo(s1));
t.add("chiru");
t.add("venky");
t.add("nagaruna");
t.add("balaiah");
t.add("saikumar");
t.add("suman");
System.out.println(t);
 }
//Scenario 2
public static void main(String arg[]) {
Set t = new TreeSet(new MyComparator1());
t.add("chiru");
t.add("venky");
t.add("nagaruna");
t.add("balaiah");
t.add("saikumar");
t.add("suman");
System.out.println(t);
}
}

class MyComparator1 implements Comparator {
public int compare(Object obj1, Object obj2) {
String s1 = (String) obj1;
String s2 = (String) obj2;
return s2.compareTo(s1);
}
}

=======================================================================
class HashCodeDemo {
int i;

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

@Override
public int hashCode() {
return i;
}

@Override
public String toString() {
return i + "";
}

public static void main(String arg[]) {
HashCodeDemo h1 = new HashCodeDemo(100);
HashCodeDemo h2 = new HashCodeDemo(110);
System.out.println(h1); // 100
System.out.println(h2); // 110
}
}
=================================================================
import java.util.ArrayList;
import java.util.Collections;

class ArrayListDemo {

//Scenario 1:

public static void main(String[] args) {

List<Integer> a =

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

Collections.sort(a);

System.out.println(a);


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

}


//Scenario 2:
public static void main(String arg[]) {
ArrayList a = new ArrayList();
a.add(10);
a.add(6);
a.add(8);
a.add(4);
a.add(2);
a.add(5);
a.add(1);
a.add(3);
a.add(7);
a.add(9);
a.add(82);
a.add(42);
Collections.sort(a);
System.out.println(a);

for (int i = 4; i <= 9; i++) {

System.out.println(a.get(i));
}
}
}

No comments:

Post a Comment