0

I have a list of objects on my software that i want to sort through a common field, example :

List<Object> obj
ID 1 Price 0.0
ID 1 Price 1.2
ID 1 Price 1.3
ID 2 Price 2.0

Can i sort the list to make the objects with ID = 1 appear only once? In this case, only the first object with ID = 1 would be left on the list, example:

ID 1 Price 0.0
ID 2 Price 2.0

How can i achieve this?

R.S.
  • 367
  • 2
  • 14

1 Answers1

1

You can easily compute a list of distinct elements if you override equals and hashCode based on your id field.

For example:

class Obj {
    private int id;
    private double price;

    public Obj(int id, double price) {
        this.id = id;
        this.price = price;
    }

    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof Obj))
            return false;

        return this.id == ((Obj) obj).id;
    }

    @Override
    public int hashCode() {
        return Integer.hashCode(id);
    }

    ...
}

And:

List<Obj> result = objects.stream().distinct().collect(Collectors.toList());
ernest_k
  • 44,416
  • 5
  • 53
  • 99