Logo

Programming-Idioms

  • Kotlin
  • C++
  • Java

Idiom #28 Sort by a property

Sort the elements of the list (or array-like collection) items in ascending order of x.p, where p is a field of the type Item of the objects in items.

import static java.util.Arrays.sort;
import static java.util.Comparator.comparing;
sort(items, comparing(x -> x.p));

Object array sort.
import java.util.Comparator;
items.stream().sorted(Comparator.comparing(x -> x.p))
import static java.util.Comparator.comparing;
items.sort(comparing(a -> a.p));

`List` sort.
import java.util.Arrays;
import java.util.Comparator;
Arrays.sort(items, new Comparator<Item>(){
	public int compare(Item a, Item b){
		return a.p - b.p;
	}
});

items is an array of type Item[].
Use an anonymous class which implements Comparator<Item>
import java.util.Collections;
import java.util.Comparator;
Collections.sort(items, new Comparator<Item>(){
	@Override
	public int compare(Item a, Item b){
		return a.p - b.p;
	}
});

items is a List<Item>.
Use an anonymous class which implements Comparator<Item>.
items.sortedBy { it.p }
#include <algorithm>
std::sort(begin(items), end(items), [](const auto& a, const auto& b) { return a.p < b.p; });

This sort is not a stable sort.
#include <algorithm>
struct {
    bool operator()(const Item &lhs, const Item &rhs) const { return lhs.p < rhs.p; }
} custom_sort;

std::sort(begin(items), end(items), custom_sort);
#include <ranges>
std::ranges::sort(items, {}, &Item::p);

Depends on C++ 20 ranges
with Ada.Containers.Vectors;
use Ada.Containers;
declare
   function Compare_Function (Left, Right : Item) return Boolean is (Left.P < Right.P);
   
   package Item_Vector_Sorting is new Item_Vectors.Generic_Sorting (Compare_Function);

   use Item_Vector_Sorting;
begin
   Sort (Items);
end;

New implementation...
< >
programming-idioms.org