Polyglot CheatSheet - Sort

Updated: 2018-06-26

Java 8+

list.stream().sorted() 

Or

list.sort((Foo o1, Foo o2) -> o1.getBar() - o2.getBar());

Reverse

list.stream().sorted(Comparator.reverseOrder())

Javascript

Sort array

arr.sort((a,b) => { return parseFloat(a.data) - parseFloat(b.data) } );

arr.sort((a,b) => { return a.str.localeCompare(b.str) } );

arr.sort((a,b) => { return a.str.toUpperCase().localeCompare(b.str.toUpperCase() } );

Sort object

const sortedObj = Object.keys(obj)
  .sort()
  .reverse()
  .reduce((newObj, k) => {
    newObj[k] = obj[k];
    return newObj;
  }, {});

Python

By default, sort, sorted, heapq can sort tuples: the first element first and on the second element second. Can specify key to override default. cmp is deprecated in Python 3

sorted_data = sorted(data, key=lambda x: x['key'])

or sorts in place

data.sort(key=lambda x: x['key'])  

Sort on multiple keys, suppose x is a tuple (int, int, boolean)

data.sort(key=lambda x: (x[0], not x[2]))

Sort dict

import operator
sorted_x = sorted(x.iteritems(), key=operator.itemgetter(1), reverse=True)