precondition:

enum Choices {a1, a2, b1, b2}

check whether if enum contains a given string

assert Arrays.asList(Choices.values()).toString().contains("a9") == false
assert Arrays.asList(Choices.values()).toString().contains("a1") == true
  • or
    assert Arrays.stream(Choices.values()).anyMatch((t) -> t.name().equals("a1")) == true
    
  • or
    assert Choices.values()*.name().contains('a1') == true
    assert Choices.values()*.name().contains('a9') == false
    
  • or

    public enum Choices {
      a1, a2, b1, b2;
    
      public static boolean contains(String s) {
        try {
          Choices.valueOf(s);
          return true;
        } catch (Exception e) {
          return false;
        }
      }
    }
    
    Choices.contains('a1')
    
  • or

    public enum Choices {
      a1, a2, b1, b2;
    
      public static boolean contains(String str) {
        return Arrays.asList(Choices.values()).toString().contains(str)
      }
    }
    assert Choices.contains('a1') == true
    

list all values in Enum

groovy:000> enum Choices {a1, a2, b1, b2}
===> true
groovy:000> println Choices.values()
[a1, a2, b1, b2]
===> null
  • or
    List<String> enumValues = Arrays.asList( Choices.values() )
    

Convert String type to Enum

groovy:000> enum Choices {a1, a2, b1, b2}
===> true
groovy:000> Choices.valueOf("a1").getClass()
===> class Choices

give Enums instance variables of their own type in Groovy

enum Direction {
  North, South, East, West, Up, Down
  private Direction opposite
  Direction getOpposite() { opposite }

  static {
    def opposites = { d1, d2 -> d1.opposite = d2; d2.opposite = d1 }
    opposites(North, South)
    opposites(East, West)
    opposites(Up, Down)
  }
}

println Direction.South.getOpposite()
println Direction.South.opposite
Direction.values().each {
  println "opposite of $it is $it.opposite"
}
  • result
    North
    North
    opposite of North is South
    opposite of South is North
    opposite of East is West
    opposite of West is East
    opposite of Up is Down
    opposite of Down is Up
    Result: [North, South, East, West, Up, Down]
    

or using the direction indexes on the enum to find the opposites

public enum Direction {
  North(1), South(0), East(3), West(2), Up(5), Down(4)
  private oppositeIndex
  Direction getOpposite() {
    values()[oppositeIndex]
  }
  Direction(oppositeIndex) {
    this.oppositeIndex = oppositeIndex
  }
}

println Direction.North.opposite

or without the need of an extra field, just using the enum values' ordinal()

enum Direction {
  North, South, East, West, Up, Down
  Direction getOpposite() {
    values()[ordinal() + ordinal() % 2 * -2 + 1]
  }
}

println Direction.North.getOpposite()
Copyright © marslo 2020-2024 all right reserved,powered by GitbookLast Modified: 2024-10-30 04:30:28

results matching ""

    No results matching ""