Skip to content

Instantly share code, notes, and snippets.

@shinchit
Created May 17, 2020 06:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shinchit/536d89279aacae82227569dbfcce58f9 to your computer and use it in GitHub Desktop.
Save shinchit/536d89279aacae82227569dbfcce58f9 to your computer and use it in GitHub Desktop.
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