我有一个枚举:
public static enum States {
SEL("Selangor"),
WP("Wilayah Persekutuan"),
KEL("Kelantan"),
LAB("Labuan"),
PER("Perlis");
private String value;
States(String val) {
this.value = val ;
}
public String getValue() {
return value;
}
}
这些值通过以下方式显示在 Thymeleaf 模板上:
<div class="col-xs-6 padding-sides-none">
<div class="form-group col-xs-12 padding-sides-none">
<label class="col-xs-2 padding-sides-none" style="margin-left:15px">State</label>
<div class="col-xs-7 padding-sides-none">
<select class="form-control selectpicker" data-live-search="true"
style="width:300px;margin-left: 50px;">
<option value="" selected disabled hidden>Please select a state</option>
<option th:each="state : ${T(com.workspez.model.Accountant.States).values()}"
th:value="${state}" th:text="${state.getValue()}">
</option>
</select>
</div>
</div>
</div>
我想按字母顺序显示值。是否可以?一种方法是手动排列枚举,但是有什么方法可以对枚举列表进行排序吗? 谢谢。
最佳答案
您可以在 States 枚举中使用 comparator
来比较和排序枚举值,如下所示:
public enum States {
SEL("Selangor"),
WP("Wilayah Persekutuan"),
KEL("Kelantan"),
LAB("Labuan"),
PER("Perlis");
private String value;
States(String val){
this.value = val ;
}
public String getValue(){
return value;
}
public static States[] getSortedValue(){
States[] values = States.values();
Arrays.sort(values,(s1,s2)->s1.getValue().compareTo(s2.getValue()));
return values;
}
}
在 thymeleaf HTML 中,只需调用 getSortedValue
方法即可按升序获取值,如下所示:
<option th:each="state : ${T(com.crud.example.enums.States).getSortedValue()}"
th:value="${state}"
th:text="${state.getValue()}">
</option>
关于java - spring thymeleaf 按字母顺序对枚举进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48841165/