LoginSignup
0
0

More than 1 year has passed since last update.

【Java】ifを使わずListの値からEnumで定義した値のみを表示する

Posted at

はじめに

業務でJavaを使うことになったが、少しブランクがあるため、記事としてまとめる。

環境

Java:11(8でも問題ない)

実装

仕様は以下の通り

  • aaa、iii、uuu以外は表示させない
  • 表示優先順位は aaa > iii > uuu
  • 重複して表示させない
呼び出し元
List<String> tests1 = new ArrayList<>();
tests1.add("aaa"); // 1番目に表示したい
tests1.add("aaa"); // 重複するので除外したい
tests1.add("uuu"); // 3番目に表示したい
tests1.add("ooo"); // 除外したい
tests1.add("eee"); // 除外したい
tests1.add("iii"); // 2番目に表示したい
tests1.add(null);  // 除外したい
tests1.add("");    // 除外したい

List<String> tests2 = TestType.getXXX(tests1);
tests2.stream().forEach(System.out::print);

// 出力結果
// aaaiiiuuu
呼び出し先のEnumクラス
@Getter
public enum TestType {

    A(1, "aaa"),
    I(2, "iii"),
    U(3, "uuu"),

    private int priority;

    private String matchString;

    private TestType(int priority, String matchString) {
        this.priority = priority;
        this.matchString = matchString;
    }

    public static List<String> getXXX (List<String> tests) {
        // 対象以外を除外して、マッチしたEnumの値をList化する
        List<TestType> targetEnums = new ArrayList<>();
        for (String test : tests) {
            TestType target = Arrays.stream(TestType.values())
                .filter(x -> x.getMatchString().equals(test))            
                .findFirst()
                .orElse(null);
            targetEnums.add(target);
        }

        // 優先度順に並び替え&重複を除外してList化
        return  targetEnums.stream()
          .filter(x -> !Objects.isNull(x)) // nullを除外
          .sorted(Comparator.comparingInt(TestType::getPriority))
          .map(x -> x.getMatchString())
          .distinct()
          .collect(Collectors.toList());
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0