Sort objects in json file (Java)

0

I have the following JSON file:

{"idAluno":1,"nomeAluno":"Teste","listaDeTurmas":[1,2,3,4]}
{"idAluno":4,"nomeAluno":"Teste","listaDeTurmas":[1,2,3,4]}
{"idAluno":3,"nomeAluno":"Teste","listaDeTurmas":[1,2,3,4]}
{"idAluno":5,"nomeAluno":"Teste","listaDeTurmas":[1,2,3,4]}
{"idAluno":2,"nomeAluno":"Teste","listaDeTurmas":[1,3,4]}

I'm using the Gson library in Java. Is it possible to sort these records incrementally in the file based on the "idAluno" field?

    
asked by anonymous 09.04.2018 / 18:27

1 answer

0

Yes, it is possible.

Just have your class use the Comparable interface. In this interface, you will define the comparison criteria.

So you can add your elements to a collection that supports sorting a>, and use the Collections.sort(testList); or Collections.reverse(testList); method, depending on the order you want. Example - Collections.sort(testList, (a, b) -> b.compareTo(a));

    
09.04.2018 / 18:32