Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Shop shop = null;
List<Shop> shops = new List<Shop>();
/* Shop A */
shop = new Shop();
shop.name = 'A shop';
shop.address = 'Minato-ku, Tokyo, Japan';
shop.proceeds = 100000;
shop.category = 'sweets';
shops.add(shop);
/* Shop B */
shop = new Shop();
shop.name = 'B shop';
shop.address = 'Kita-ku, Osaka, Japan';
shop.proceeds = 110000;
shop.category = 'sweets';
shops.add(shop);
/* Shop C */
shop = new Shop();
shop.name = 'C shop';
shop.address = 'NewYork, US';
shop.proceeds = 90000;
shop.category = 'diy';
shops.add(shop);
shops.sort();
System.debug(shops);
public class Shop implements Comparable {
public String name{get; set;}
public String address{get; set;}
public Long proceeds{get; set;}
public String category{get; set;}
public Integer compareTo(Object other) {
// sort by category asc
Integer categoryCompared = category.compareTo(((Shop)other).category);
// next, sort by proceeds desc
Integer proceedsCompared = categoryCompared != 0 ? categoryCompared : (Integer)(((Shop)other).proceeds - proceeds);
// next, sort by address asc
Integer addressCompared = proceedsCompared != 0 ? proceedsCompared : address.compareTo(((Shop)other).address);
return addressCompared;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment