场景:一个枚举,我需要返回字典列表
要求1:对枚举类型进行转化
要求2:返回的值,根据 key 升序排列
-----------------------------------
话不多说,直接撸代码
EnumTest.java 内容如下:
package com.lianjia.mls.support.web.controller; import lombok.AllArgsConstructor; import lombok.Getter; import java.util.HashMap; import java.util.Map; @AllArgsConstructor @Getter public enum EnumTest { test_add_test("001", "字典1"), test_del_test("002", "字典2"), test003("003", "字典3"), test_update_test("006", "字典623"), test005("005", "字典523"), test004("004", "字典4"), test020("020", "字典20"), ; private String code; private String desc; private static final Map<String, EnumTest> allTypeMap = new HashMap<>(); static { for (EnumTest enumTest : values()) { allTypeMap.put(enumTest.getCode(), enumTest); } } public static Map<String, EnumTest> getAllTypeWithMap() { return allTypeMap; } }
TestMain.java
package com.lianjia.mls.support.web.controller; import com.google.common.collect.ImmutableSortedMap; import com.google.common.collect.Maps; import java.util.Map; public class TestMain { public static void main(String[] args) { //未排序 Map<String, String> resultNoSort = Maps.transformValues(EnumTest.getAllTypeWithMap(), enumTest -> enumTest.getDesc()); System.out.println(resultNoSort); //已排序 Map<String, String> resultSorted = ImmutableSortedMap.<String, String>naturalOrder() .putAll(Maps.transformValues(EnumTest.getAllTypeWithMap(), enumTest -> enumTest.getDesc())).build(); System.out.println(resultSorted); } }
使用 guava 强大的功能,可以使代码变得更加简洁!!!
参考:http://www.91r.net/ask/4906961.html