Help more people learn by sharing this post!

Tag Archives for " sorting "

Sorting Java Collections

Java collections are most of the data structures that come with the language. They share the same basics methods thanks to the collection interface. One of the most common things you may want to do with a collection, besides adding and removing elements, is sorting them.

Let’s see an example with ArrayList
Continue reading

Alphanumeric sorting

Time for a bit more sorting. Today our task is to sort an array of file names based on the numeric value. This what the array looks like:

If you try a simple sort it won’t come out as you expect…

Ruby sort by value

This is not what we want, so we will have to reach for sort_by again:

And this time we get what we want. What we are doing here is taking each element of the array and using a regexp to scan for decimal numbers (\d+ or also [0-9]+) since we get an string back we need to convert it to a number with to_i. Hope you find it useful.

Ruby-doc: http://ruby-doc.org/core-1.9.3/Enumerable.html#method-i-sort_by

Ruby: fine grained sorting

Ruby sorting is really easy, lets see some examples. If we had this array: ["abc", "aaa", "add", "bcc", "baa"] sorting normally we would get:

Let’s say we wanted to sort by the second letter, we could do this using the sort_by method:

Now lets see a more complex example, if we wanted to sort an email list:

First by the host name and then by the user name we can use the sort_by method like this:

We pass a block to sort_by with the ‘rules’ we want to sort by, we are using a regular expression to express how we want to sort, they are /@./ which matches everything after the at sign and /.@/ which matches everything before.

Finally we can apply the same idea to uniq so that we can get unique data based on a pattern, I use this in Dirfuzz to filter the results and avoid duplicates when I have duplicate results that aren’t exactly the same.

This regexp will allow me to get rid of duplicates with this data:

This would stay the same with a simple uniq, but passing a block with that regexp will get rid of the duplicates.