Sorting a List of a Custom Type

Sort a Custom Class ListT

One way to do this is with a delegate

List<cTag> week = new List<cTag>();
// add some stuff to the list
// now sort
week.Sort(delegate(cTag c1, cTag c2) { return c1.date.CompareTo(c2.date); });

List.Sort (Custom sorting...)

Linq is great for this. You could even build the order sequence up to have it defined on the fly since the execution of the sort is not executed until the ToList.

 var sortedList = yourList.OrderBy(i => i.FullToH).
ThenBy(i => i.Partial).
ThenBy(i => i.FullToO).ToList();

Sort a list by a custom order

Assuming linkTypes (the private string array) is in the same class as links (the list of LinkElement), you can use LINQ's OrderBy with a simple lambda expression:

var sortedLinks = links.OrderBy(le => Array.IndexOf(linkTypes, le.linkType)).ToList()

Sorting a list of a custom type

You can specify a custom sort predicate. In C++11 this is best done with a lambda:

typedef std::pair<int, int> ipair;
std::list<ipair> thelist;

thelist.sort([](const ipair & a, const ipair & b) { return a.first < b.first; });

In older versions of C++ you have to write an appropriate function:

bool compFirst(const ipair & a, const ipair & b) { return a.first < b.first; }

thelist.sort(compFirst);

(Instead if ipair you can of course have your own data structure; just modify the comparison function accordingly to access the relevant data member.)

Finally, if this makes sense, you can also equip your custom class with an operator<. That allows you to use the class freely in any ordered context, but be sure to understand the consequences of that.

Sorting a list of custom data types by certain attribute in Haskell

The easiest and most flexible way to deal with that problem, given that there are multiple valid ways to sort Person values, is not by changing the Ord instance, but by using a custom sorting function.

import Data.List (sortBy)
import Data.Ord (comparing)

sortByAge :: [Person] -> [Person]
sortByAge = sortBy (comparing age)

sortBy :: (a -> a -> Ordering) -> [a] -> [a] makes a custom sorting function from a comparison function, while comparing :: Ord a => (b -> a) -> b -> b -> Ordering makes such a comparison function given, for instance, a field acessor. Be sure to have a good look at the involved type signatures in order to grok how everything fits together.

If you do need to change the Ord instance, here is how it would go. The syntax is as follows:

instance Ord Person where
compare = undefined -- placeholder

The documentation tells us that, from all of the Ord methods, we just need to implement compare. Now, what should we replace undefined with? We want the comparison to be based on age, which is an Int field. Since Int is an instance of Ord, the answer is immediate:

instance Ord Person where
compare x y = compare (age x) (age y)

Incidentally, the definition of comparing is:

comparing :: (Ord a) => (b -> a) -> b -> b -> Ordering
comparing p x y = compare (p x) (p y)

And so we could write the instance in the style we used for the first solution:

instance Ord Person where
compare = comparing age

Sort ArrayList of custom Objects by property

Since Date implements Comparable, it has a compareTo method just like String does.

So your custom Comparator could look like this:

public class CustomComparator implements Comparator<MyObject> {
@Override
public int compare(MyObject o1, MyObject o2) {
return o1.getStartDate().compareTo(o2.getStartDate());
}
}

The compare() method must return an int, so you couldn't directly return a boolean like you were planning to anyway.

Your sorting code would be just about like you wrote:

Collections.sort(Database.arrayList, new CustomComparator());

A slightly shorter way to write all this, if you don't need to reuse your comparator, is to write it as an inline anonymous class:

Collections.sort(Database.arrayList, new Comparator<MyObject>() {
@Override
public int compare(MyObject o1, MyObject o2) {
return o1.getStartDate().compareTo(o2.getStartDate());
}
});


Since java-8

You can now write the last example in a shorter form by using a lambda expression for the Comparator:

Collections.sort(Database.arrayList, 
(o1, o2) -> o1.getStartDate().compareTo(o2.getStartDate()));

And List has a sort(Comparator) method, so you can shorten this even further:

Database.arrayList.sort((o1, o2) -> o1.getStartDate().compareTo(o2.getStartDate()));

This is such a common idiom that there's a built-in method to generate a Comparator for a class with a Comparable key:

Database.arrayList.sort(Comparator.comparing(MyObject::getStartDate));

All of these are equivalent forms.

Sort list containing custom type on new add

Use the SortedList and use Foo.Order as key for the list.



Related Topics



Leave a reply



Submit