[英]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.