I have list of months, I am setting in the POJO class, While I am setting it, order is not getting sorted. I want to sort it. Sample data looks like -
My POJO Class -
public class SamplePojo {
private static final long serialVersionUID = 1L;
private String type;
private String name;
private Integer January;
private Integer February;
private Integer March;
private Integer April;
private Integer May;
private Integer June;
}
ServiceImpl -
List<SamplePojo> sp = new ArrayList<SamplePojo>();
SamplePojo tp1 = new SamplePojo ();
tp1.type("type");
tp1.name("name");
tp1.setJanuary(12);
tp1.setFebruary(2);
tp1.setMarch(33);
tp1.setApril(0);
tp1.setMay(0);
tp1.setJune(0);
tp1.setTotal(122);
sp.add(tp1);
Unsorted data -
[
{
"type": "LLB",
"name": "Working",
"total": 0,
"march": 33,
"april": 0,
"may": 0,
"june": 0,
"february": 2,
"january": 12
},
{
"type": "Engineer",
"name": "Not Working",
"total": 0,
"march": 33,
"april": 0,
"may": 0,
"june": 0,
"february": 2,
"january": 12
}
]
Wanted to sort -
[
{
"type": "LLB",
"name": "Working",
"january": 11,
"february": 2,
"march": 3,
"april": 3,
"may": 0,
"june": 0,
"total": 0
},
{
"type": "Engineer",
"name": "Not Working",
"january": 12,
"february": 2,
"march": 33,
"april": 0,
"may": 0,
"june": 0,
"total": 0
}
]
How can I do this using Spring boot. I am new to this Spring boot and New to this stackoverflow. Can you please help me out.
CodePudding user response:
Try to sort using java 8 its not clear on question which fields need to sorted
list.sort(Comparator.comparing(SamplePojo ::getType));// if sort by type
CodePudding user response:
The best way to do this is sorting from the repository by using Spring Data Repository query keywords by find all SampleEntity
by following code.
@Repository
public interface SampleEntityRepository extends JpaRepository<SampleEntity, Long> {
List<SampleEntity> findAllByOrderByJanuaryAsc();
}
But if you want to sort on the last layer to showing List of SamplePojo
you can use stream
and sorted
by some criteria.
List<SamplePojo> lastList = sampleService.findAll();
lastList
.stream()
.sorted((sPojo1, sPojo2) -> sPojo1.getJanuary().compareTo(sPojo2.getJanuary()));