Search code examples
javacollectionsguava

Filter and sort items of a generic list in Java


I'm implementing search, sorting and pagination logic for a web application and I need to find an efficient and possibly not verbose way to sort and filter items of a generic type list (List<T>). I would like to dynamally pass the field by which the list will be sorted (as a string, for example).

Is it a good idea to use Guava libraries or can I achieve the same result using standard java libraries? I've never used Guava and I would avoid adding additional libraries to my project if I'll going to use them only for minor utilities.

Note I'm also using Spring in my project. Is there some helpful utility to handle collections?

In .NET applications I usually use LINQ to manupulate and query collections, I'd like to find something similar or at least a simple alternative to this approach... can you help me?

NOTE I need to sort custom objects by an arbitrary field, so if I have a Person object with name, surname and age fields, I need to sort the list by one of these.


Solution

  • The standard Java libraries provide Collections.sort() for one-shot sorting and TreeSet and TreeMap for permanently sorted collections.

    Either the objects inside the collections need to implement comparable (in which case the default behavior of all of the above is to sort using natural ordering) or you can specify a Comparator to the sort operation (or Tree*). If you do specify a Comparator it over-rides the default sorting behavior and completely replaces it.