I was going through the exercises in Java 8 in Action and I came across this question. There are 2 classes Trader and Transaction described as follows:
public class Trader {
    private final String name;
    private final String city;
    public Trader(String n, String c) {
        this.name = n;
        this.city = c;
    }
    public String getName() {
        return this.name;
    }
    public String getCity() {
        return this.city;
    }
    public String toString() {
        return "Trader:" + this.name + " in " + this.city;
    }
}
public class Transaction {
    private final Trader trader;
    private final int year;
    private final int value;
    public Transaction(Trader trader, int year, int value) {
        this.trader = trader;
        this.year = year;
        this.value = value;
    }
    public Trader getTrader() {
        return this.trader;
    }
    public int getYear() {
        return this.year;
    }
    public int getValue() {
        return this.value;
    }
    public String toString() {
        return "{" + this.trader + ", " + "year: " + this.year + ", " + "value:" + this.value + "}";
    }
}
Traders and a list of transactions are created as follows:
        Trader mario = new Trader("Mario", "Milan");
        Trader alan = new Trader("Alan", "Cambridge");
        Trader brian = new Trader("Brian", "Cambridge");
        Trader raoul = new Trader("Raoul", "Cambridge");
        List<Transaction> transactions = Arrays.asList(new Transaction(brian, 2011, 300),
                new Transaction(raoul, 2012, 1000), new Transaction(raoul, 2011, 400),
                new Transaction(mario, 2012, 710), new Transaction(mario, 2012, 700), new Transaction(alan, 2012, 950));
The question is to find all traders from Cambridge and sort them by name. The solution given to this problem in the book is as follows:
List<Trader> traders = transactions.stream()
                               .map(Transaction::getTrader)
                               .filter(trader -> trader.getCity().equals("Cambridge"))
                               .distinct()
                               .sorted(comparing(Trader::getName))
                               .collect(toList());
The answer provided above returns the correct results but I was wondering how and why is distinct() using the name field to return distinct traders?
 
     
    