[英]How to sort months in List<> in Spring boot - Using Java 8
我有月份列表,我在 POJO class 中设置,在设置时,订单没有排序。 我想整理一下。 样本数据看起来像 -
我的 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);
未排序的数据 -
[
{
"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
}
]
想要排序 -
[
{
"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
}
]
如何使用 Spring 启动来做到这一点。 我是这个 Spring 启动的新手,也是这个 stackoverflow 的新手。 你能帮帮我吗?
如果要对 JSON 有效载荷进行排序,可以使用@JsonPropertyOrder
注解
@JsonPropertyOrder({
"type",
"name",
"January",
"February",
"March"
})
public class SamplePojo {
private static final long serialVersionUID = 1 L;
private String type;
private String name;
private Integer January;
private Integer February;
private Integer March;
private Integer April;
private Integer May;
private Integer June;
}
最好的方法是使用Spring Data Repository 查询关键字从存储库中排序,通过以下代码查找所有SampleEntity
。
@Repository
public interface SampleEntityRepository extends JpaRepository<SampleEntity, Long> {
List<SampleEntity> findAllByOrderByJanuaryAsc();
}
但是,如果您想在最后一层排序以显示List of SamplePojo
您可以使用stream
并按某些标准sorted
。
List<SamplePojo> lastList = sampleService.findAll();
lastList
.stream()
.sorted((sPojo1, sPojo2) -> sPojo1.getJanuary().compareTo(sPojo2.getJanuary()));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.