0

I have a list of objects that I get from the database, and I need to order it by a field, but I can't apply the order criteria on the orderby clause, I need to do it on java.

List<Cliente> listaClientesPorNomAp = new ArrayList<Cliente>();
listaClientesPorNomAp = (List<Cliente>) getSqlMapClientTemplate().queryForList("CLIENTES.obtenerClientesFiltroPorNomAndAp", filtroPaginacion);

List<Cliente> nonFilteredList = new ArrayList<Cliente>();
nonFilteredList.addAll(listaClientesPorNomAp);
HashSet<Cliente> filteredSet = new HashSet<Cliente>(nonFilteredList);

I want to order the list of 'Cliente' by the attribute docNumber. How can I do it?

Thanks!

Julia
  • 538
  • 2
  • 7
  • 17
  • 1
    a `Set` implementation might not preserve order so when you convert your list to a `Set` the order might be lost – Lino Dec 14 '17 at 12:55
  • @Lino `TreeSet` and `LinkedHashSet` will preserve order and can be sorted – XtremeBaumer Dec 14 '17 at 12:58
  • What about [`Collections.sort`](https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#sort-java.util.List-java.util.Comparator-) ? Like this [answer](https://stackoverflow.com/a/34646172/4391450) – AxelH Dec 14 '17 at 12:58
  • 1
    @XtremeBaumer you're right i meant to say that, but had a translation error. I meant *might not* instead of *must not* – Lino Dec 14 '17 at 12:59
  • And how can I choose the field I want to sort by? – Julia Dec 14 '17 at 12:59
  • "I can't apply the order criteria on the orderby clause" why not? You're also creating multiple lists that are immediately thrown away or just unnecessary. – Kayaman Dec 14 '17 at 13:00
  • you could use a comparator HashSet filteredSet = new LinkedHashSet(nonFilteredList); // because sets have no order Collections.sort(filteredSet, new Comparator(){ public int compare(Cliente c1, Cliente c2) { return c1.field1 - c2.field2; // if you compare values, you can change this line based on your field you compare } }); – Stelium Dec 14 '17 at 13:02
  • `Collections.sort(list, (c1, c2) -> c2.getDocNumber() - c1.getDocNumber());` should do the trick. A stream could be used but I fould the solution much more verbose... – AxelH Dec 14 '17 at 13:04
  • You could use stream API to create sorted set. `nonFilteredList.stream().sorted((c1, c2) -> Integer.compare(c1.getDocNumber(), c2.getDocNumber())).collect(Collectors.toSet())` – Uladzislau Kaminski Dec 14 '17 at 13:04
  • @Kayaman I didn't paste the full code, I need to do it because I have to merge different lists into one, i just pasted the code from one because I think it's enough – Julia Dec 14 '17 at 13:10

0 Answers0