Stream Api Distinct Keyword usage

import java.util.ArrayList;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

public class CoffeeShop {
    private String name;

    public CoffeeShop(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        CoffeeShop that = (CoffeeShop) o;
        return Objects.equals(name, that.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name);
    }

    public static void main(String[] args) {
        ArrayList<CoffeeShop> coffeeShops = new ArrayList<>();
        coffeeShops.add(new CoffeeShop("Pret A Manger"));
        coffeeShops.add(new CoffeeShop("Costa Coffee"));
        coffeeShops.add(new CoffeeShop("Starbucks"));
        coffeeShops.add(new CoffeeShop("Pret A Manger"));
        coffeeShops.add(new CoffeeShop("Costa Coffee"));

        Set<CoffeeShop> uniqueCoffeeShops = coffeeShops.stream().distinct().collect(Collectors.toSet());

        System.out.println(uniqueCoffeeShops); // Output: [CoffeeShop{name='Pret A Manger'}, CoffeeShop{name='Costa Coffee'}, CoffeeShop{name='Starbucks'}]
    }
}

Bir cevap yazın

E-posta hesabınız yayımlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir