- public enum TestEnum {
- CODE_11("CODE_11","测试1"),
- CODE_22("CODE_22","测试2"),
- CODE_33("CODE_33","测试3"),
- CODE_44("CODE_44","测试4"),
- CODE_55("CODE_55","测试5"),
- ;
-
- private String code;
- private String name;
-
- TestEnum(String code, String name) {
- this.code = code;
- this.name = name;
- }
-
- public String getCode() {
- return code;
- }
-
- public String getName() {
- return name;
- }
- }
1.获取所有枚举值,并转map
- public static void main(String[] args) {
- TestEnum[] values = TestEnum.values();
-
- Map<String, String> map = Arrays.stream(values).collect(Collectors.toMap(i -> i.getCode(), i -> i.getName()));
-
- System.out.println(map);
- }
控制台输出:
{CODE_55=测试5, CODE_44=测试4, CODE_33=测试3, CODE_22=测试2, CODE_11=测试1}
2.根据key排序
- public static void main(String[] args) {
- TestEnum[] values = TestEnum.values();
-
- Map<String, String> map = Arrays.stream(values)
- .collect(Collectors.toMap(i -> i.getCode(), i -> i.getName())).entrySet()
- .stream().sorted((e1, e2) -> e1.getKey().compareTo(e2.getKey()))
- .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,(e1, e2) -> e1, LinkedHashMap::new));
-
- System.out.println(map);
- }
控制台输出:
{CODE_11=测试1, CODE_22=测试2, CODE_33=测试3, CODE_44=测试4, CODE_55=测试5}
3.查找
- public static void main(String[] args) {
- TestEnum[] values = TestEnum.values();
-
- Map<String, String> map = Arrays.stream(values)
- .collect(Collectors.toMap(i -> i.getCode(), i -> i.getName())).entrySet().stream()
- .filter(e ->e.getKey().equals("CODE_33"))
- .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,(e1, e2) -> e1, LinkedHashMap::new));
-
- System.out.println(map);
- }
控制台输出:
{CODE_33=测试3}
4.模糊查询
- public static void main(String[] args) {
- TestEnum[] values = TestEnum.values();
-
- Map<String, String> map = Arrays.stream(values)
- .collect(Collectors.toMap(i -> i.getCode(), i -> i.getName())).entrySet().stream()
- .filter(e ->e.getKey().contains("2"))
- .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,(e1, e2) -> e1, LinkedHashMap::new));
-
- System.out.println(map);
- }
控制台输出:
{CODE_33=测试3}