Sunday, 15 December 2024

Custom Comparator using java8 streams

 



l

Why override equals() and hashCode()?

  • equals(): Determines whether two objects are considered equal. When you add an object to a Set, the set uses this method to check if an object already exists in the set.
  • hashCode(): Provides a hash code that is used for efficient lookups in hash-based collections like HashSet. If you override equals(), you should also override hashCode() to maintain the general contract between these methods.



1 ) import java.util.HashSet;

import java.util.Set;


class Person {

    private String name;

    private int age;


    // Constructor

    public Person(String name, int age) {

        this.name = name;

        this.age = age;

    }


    // Getters

    public String getName() {

        return name;

    }


    public int getAge() {

        return age;

    }


    // Override equals() to compare name and age for equality

    @Override

    public boolean equals(Object o) {

        if (this == o) return true;

        if (o == null || getClass() != o.getClass()) return false;

        Person person = (Person) o;

        return age == person.age && name.equals(person.name);

    }


    // Override hashCode() to generate a consistent hash code based on name and age

    @Override

    public int hashCode() {

        return 31 * name.hashCode() + Integer.hashCode(age);

    }


    @Override

    public String toString() {

        return "Person{name='" + name + "', age=" + age + '}';

    }

}


public class Main {

    public static void main(String[] args) {

        // Create a Set of Person objects

        Set<Person> people = new HashSet<>();


        // Add some custom objects to the Set

        people.add(new Person("Alice", 30));

        people.add(new Person("Bob", 25));

        people.add(new Person("Alice", 30)); // Duplicate (same name and age)

        people.add(new Person("Charlie", 35));


        // Output the set to see unique objects

        for (Person person : people) {

            System.out.println(person);

        }

    }

}

 


2 )

import java.util.Set;

import java.util.TreeSet;

import java.util.Comparator;


class Person {

    private String name;

    private int age;


    // Constructor

    public Person(String name, int age) {

        this.name = name;

        this.age = age;

    }


    // Getters

    public String getName() {

        return name;

    }


    public int getAge() {

        return age;

    }


    @Override

    public String toString() {

        return "Person{name='" + name + "', age=" + age + '}';

    }

}


public class Main {

    public static void main(String[] args) {

        // Comparator to sort by name in ascending order

        Comparator<Person> nameComparator = (p1, p2) -> p1.getName().compareTo(p2.getName());


        // Create a TreeSet with a custom comparator (sorting by name)

        Set<Person> people = new TreeSet<>(nameComparator);


        // Add some custom objects to the Set

        people.add(new Person("Alice", 30));

        people.add(new Person("Bob", 25));

        people.add(new Person("Charlie", 35));


        // Output the set to see ordered elements

        for (Person person : people) {

            System.out.println(person);

        }

    }

}



3 ) 

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

class Person {
    private String name;
    private int age;

    // Constructor
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // Getters
    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    // Override equals() and hashCode() for unique elements in Set
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return age == person.age && name.equals(person.name);
    }

    @Override
    public int hashCode() {
        return 31 * name.hashCode() + Integer.hashCode(age);
    }

    @Override
    public String toString() {
        return "Person{name='" + name + "', age=" + age + '}';
    }
}

public class Main {
    public static void main(String[] args) {
        List<Person> peopleList = Arrays.asList(
                new Person("Alice", 30),
                new Person("Bob", 25),
                new Person("Alice", 30),  // Duplicate
                new Person("Charlie", 35)
        );

        // Using Stream to add unique custom objects to a Set
        Set<Person> uniquePeople = peopleList.stream()
                .collect(Collectors.toSet()); // Collect into a Set to ensure uniqueness

        // Output the unique Set
        uniquePeople.forEach(System.out::println);
    }
}


4 ) 
import java.util.*;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        List<Person> peopleList = Arrays.asList(
                new Person("Alice", 30),
                new Person("Bob", 25),
                new Person("Charlie", 35)
        );

        // Using Stream to sort by name (custom Comparator)
        List<Person> sortedByName = peopleList.stream()
                .sorted(Comparator.comparing(Person::getName)) // Sorting by name
                .collect(Collectors.toList());

        // Output the sorted list
        sortedByName.forEach(System.out::println);
    }
}

5 ) import java.util.*;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        List<Person> peopleList = Arrays.asList(
                new Person("Alice", 30),
                new Person("Bob", 25),
                new Person("Charlie", 35)
        );

        // Using Stream to map Person objects to their names
        List<String> names = peopleList.stream()
                .map(Person::getName) // Map Person to String (name)
                .collect(Collectors.toList());

        // Output the mapped names
        names.forEach(System.out::println);
    }
}

No comments:

Post a Comment