Showing posts with label Core Java. Show all posts
Showing posts with label Core Java. Show all posts

Thursday 15 June 2023

How to sort a list of objects in java 8 with stream?

 In Java 8, you can use the Stream API to sort a list of Employee objects based on name and ID. Here's an example:

java
import java.util.ArrayList; 
import java.util.Comparator; 
import java.util.List; 
class Employee
private int id; 
private String name;
public Employee(int id, String name) {
this.id = id; 
this.name = name;
 }
public int getId()
return id; 
 } 
public String getName()
return name; 
 } 
@Override public String toString() {
return "Employee{" + "id=" + id + ", name='" + name + '\'' + '}'
 } 
public class EmployeeSortingExample {
public static void main(String[] args)
 List<Employee> employees = new ArrayList<>(); 
 employees.add(new Employee(3, "John")); 
 employees.add(new Employee(1, "Alice")); 
 employees.add(new Employee(2, "Bob")); 
// Sort by name List<Employee> sortedByName = employees.stream() .sorted(Comparator.comparing(Employee::getName)) .toList();
 System.out.println("Sorted by name:");
 sortedByName.forEach(System.out::println);
// Sort by ID List<Employee> sortedById = employees.stream() .sorted(Comparator.comparingInt(Employee::getId)) .toList(); System.out.println("Sorted by ID:"); sortedById.forEach(System.out::println); 
 } 
}

In this example, we use the stream() method to convert the List of employees into a stream. Then we use the sorted method along with a comparator created using Comparator.comparing() to specify the property to sort on (Employee::getName for name and Employee::getId for ID).

The sorted method returns a new sorted stream, and we use the toList method to collect the sorted elements into a new List.

After sorting the streams and collecting the sorted elements into new lists, we use the forEach method to iterate over the sorted lists and print the employees' details. The System.out::println method reference is used as a lambda expression to print each employee.

How many ways are there to create object in java?

In Java, there are several ways to create objects. Here are the most common ways:

  1. Using the new keyword: The new keyword is used to create a new instance of a class. It invokes the class constructor and allocates memory for the object. For example:

    java
    MyClass obj = new MyClass();
  2. Using reflection: Reflection allows you to create objects dynamically at runtime. It provides classes like Class and Constructor that can be used to create objects without knowing the class name at compile-time. Here's an example:

    java
    Class<?> clazz = Class.forName("MyClass"); MyClass obj = (MyClass) clazz.newInstance();
  3. Using clone: The clone method creates a copy of an existing object. To use this approach, the class must implement the Cloneable interface and override the clone method. Here's an example:

    java
    MyClass originalObj = new MyClass(); MyClass clonedObj = originalObj.clone();
  4. Using deserialization: Deserialization is the process of converting an object from its serialized form (e.g., byte stream) back into an object. It allows you to recreate objects from stored data. Here's an example:

    java
    FileInputStream fileIn = new FileInputStream("object.ser"); ObjectInputStream in = new ObjectInputStream(fileIn); MyClass obj = (MyClass) in.readObject(); in.close(); fileIn.close();
  5. Using static factory methods: Some classes provide static factory methods that create and return instances of the class. These methods have names like getInstance(), valueOf(), or newInstance(). They provide flexibility in object creation. Here's an example:

    java
    MyClass obj = MyClass.getInstance();

These are some common ways to create objects in Java. The appropriate method depends on the specific requirements of your application.