Sort Collection

Asked

Viewed 1,259 times

0

I have a class called Object and within it possesses a Collection of Events, so to sum up:

public class Objeto{

private Collection<Evento> eventos;
}

In the Event class, I have my attributes and among them, I own a:

@Getter
    @Setter
    @Column
    @Temporal(TemporalType.TIMESTAMP)
    private Date horario;

On my screen I’ll get a Collection of Object. I need the following:

If in my Event class that is within Object I own the field horario. I need my Collection Object is ordered in descending order to horario. Ex:

10/12/2015 10:00
10/12/2015 09:00
...

I tried so but unsuccessfully:

@SuppressWarnings("deprecation")
    public Collection<Objeto> ordenarLista() {
        Collection<Objeto> objetos = service.findAll();
        Collection<Objeto> lista = new ArrayList<Objeto>();
        Date referencia = new Date("10/01/2000 00:00:00");
        for (Objeto objeto : objetos) {
            for (Evento evento : objeto.getEventos()){
                if (evento.getHorario().after(referencia)){
                    lista.add(objeto);
                    referencia = evento.getHorario();
                }
            }
        }
        return lista;
    }

Does anyone know how I can solve ?

  • would like to add an Addendum on Arraylist: here. I believe I can help you understand your question. In your solution you use the Collection interface which in turn is the parent interface of the List interface.

2 answers

1

If you are using Java 8, you can do the following:

List<Evento> lista = new ArrayList<>(service.findAll());
lista.sort(new Comparator<Evento>() {
    @Override
    public int compare(Evento o1, Evento o2) {
        return o1.getHorario().compareTo(o2.getHorario());
    }
});
return lista;

If you’re using Java 7 or earlier, there’s also Collections.sort:

List<Evento> lista = new ArrayList<>(service.findAll());
Collections.sort(lista, new Comparator<Evento>() {
    @Override
    public int compare(Evento o1, Evento o2) {
        return o1.getHorario().compareTo(o2.getHorario());
    }
});
return lista;

Note that the example is not null-safe, but this is a quick treatment normally

EDIT

Douglas realized that my suggestions have problems. Whereas within Objeto have a List of Evento, it is wanted that the Objeto that has the latest event appear in the freight:

List<Objecto> objetos = new ArrayList<>(service.findAll());
// ordenar todos os eventos dentro de cada objeto
for (Objeto obj: objetos) {
    obj.getEventos().sort(new Comparator<Evento>() {
        @Override
        public int compare(Evento o1, Evento o2) {
            // invertendo a ordem, primeiro os eventos maiores
            return -o1.getHorario().compareTo(o2.getHorario());
        }
    });
}
// ordenar usando como base o maior dos eventos
objetos.sort(new Comparator<Objeto>() {
        @Override
        public int compare(Objeto o1, Objeto o2) {
            // levando em comparação os maiores eventos que, devido à ordenação anterior, estão em obj.getEventos().get(0)
            return -o1.getEventos().get(0).getHorario().compareTo(o2.getEventos().get(0).getHorario());
        }
    });
  • 1

    My findAll returns Object list and not Event list.

  • Define a way of how you want to order the Objeto then. I believe that in Objeto you want a bag (bag: multiconjunto, https://pt.wikipedia.org/wiki/Multiconjunto) sorted, so in these cases, you should use List, not only Collection. From what I read, you want to order Objeto using his Evento which happens later, that’s it:

  • Exactly, I even switched from Collection to List.

  • Douglas, I changed my answer. Look over there EDIT, should meet your needs. Anything, has a Caelum post teaching you how to use the Comparator in Java: http://blog.caelum.com.br/sort/

  • 1

    @Jeffersonquesado, I’d like to add an addendum on Arraylist: here. I believe it can help in understanding your answer. In your solution you use the Arraylist object which in turn is an object of the List interface.

0

Utilize features of Java 8, as method References, to simplify the work, as follows:

List<Evento> eventos = objeto.getEventos();
eventos.sort(Comparator.comparing(Evento::getHorario))

In this case the event list will be ordered in ascending order of Horario.

As you want decreasing, use the comparator reversed:

List<Evento> eventos = objeto.getEventos();
eventos.sort(Comparator.comparing(Evento::getHorario).reversed())
  • Thanks for the reply. But I want to sort the list of objects, will work in this case ?

  • Yes. If you are using Java 8, in List has the method sort(Comparator), where you pass the desired command and the list is sorted. Note that Collection is a bag disordered; ordered things implement List

  • Are you sure? What time do I change the Objects List ?

  • @Murillogoulart, I’d like to add an addendum on Arraylist: here. I believe it can help in understanding your answer. In your solution you use the List interface.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.