java中list集合根据枚举类型排序

自定义枚举类

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import java.util.Arrays;
@Getter
@NoArgsConstructor
@AllArgsConstructor
public enum ProContant {

    QCC("QCC",1),
    FQCC("FQCC",2),
    HELIHUA("合理化",3),
    TOPN("TOPN",4),
    HEIDAI("黑带",5),
    LVDAI("绿带",6);

    private String key;
    private Integer index;

   public static ProContant getProContant(String str) {
       return Arrays.stream(ProContant.values())
               .filter(proContant -> str.equals(proContant.getKey()))
               .findFirst()
               .orElse(null);
   }
}

测试

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Test {
    public static void main(String[] args) {
        List list = Arrays.asList("绿带", "合理化", "黑带", "QCC", "FQCC", "TOPN");
        System.out.println("原集合:"+list);
        Collections.sort(list, new Comparator() {
            @Override
            public int compare(String o1, String o2) {
                return ProContant.getProContant(o1).getIndex() - ProContant.getProContant(o2).getIndex();
            }
        });
        System.out.println("排序后的集合"+list);
    }
}

简写方式

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class Test {
    public static void main(String[] args) {
        List list = Arrays.asList("绿带", "合理化", "黑带", "QCC", "FQCC", "TOPN");
        System.out.println("原集合:"+list);
        list.sort(Comparator.comparingInt(o -> ProContant.getProContant(o).getIndex()));
        System.out.println("排序后的集合:"+list);
    }
}

运行结果:
原集合:[绿带, 合理化, 黑带, QCC, FQCC, TOPN]
排序后的集合:[QCC, FQCC, 合理化, TOPN, 黑带, 绿带]

你可能感兴趣的:(11,java)