我在Java中有一个用于基数和中间方向的枚举:
public enum Direction {
NORTH,
NORTHEAST,
EAST,
SOUTHEAST,
SOUTH,
SOUTHWEST,
WEST,
NORTHWEST
}
我怎么能写一个循环,遍历每一个这些枚举值?
我在Java中有一个用于基数和中间方向的枚举:
public enum Direction {
NORTH,
NORTHEAST,
EAST,
SOUTHEAST,
SOUTH,
SOUTHWEST,
WEST,
NORTHWEST
}
我怎么能写一个循环,遍历每一个这些枚举值?
当前回答
我们可以像这样使用一个过滤器(JAVA 8)。
Stream.of(Direction.values()).filter(name -> !name.toString().startsWith("S")).forEach(System.out::println);
其他回答
场景:假设,我们有固定数量的纸牌类型。 每种卡类型都有费用和与之相关的加入奖金。
package enumPkg;
public enum CardTypes {
//Each enum is object
DEBIT(10,20),
CREDIT(0,10),
CRYPTO(5,30);
//Object properties
int fees;
int bonus;
//Initilize object using constructor
CardTypes(int fee, int bonus){
this.fees = fee;
this.bonus = bonus;
}
//access object property
public int getFees(){
return this.fees;
}
public int getBonus(){
return this.bonus;
}
}
现在在其他类中访问enum。在java中遵循以下过程:
package enumPkg;
public class EnumClass {
public static void main(String[] args) {
CardTypes cardType = CardTypes.CREDIT; //Each enum element is public static final, when accessed returns a object
System.out.println(cardType);
System.out.println("Debit card fees : "+CardTypes.DEBIT.getFees());
System.out.println("Debit card bonus : "+CardTypes.DEBIT.getBonus());
CardTypes[] cardTypes = CardTypes.values();//return array of CardTypes i.e all enum elements we have defined
for (CardTypes type : CardTypes.values()) {
System.out.println(type); //particular enum object
System.out.println(type.ordinal()); //return enum position
System.out.println("Bonus : "+type.getBonus()); //return enum object property: Bonus
System.out.println("Fees : "+type.getFees());//return enum object property: Fees
}
}
}
输出:
CREDIT
Debit card fees : 10
Debit card bonus : 20
DEBIT
0
Bonus : 20
Fees : 10
CREDIT
1
Bonus : 10
Fees : 0
CRYPTO
2
Bonus : 30
Fees : 5
java 8中的更多方法:
使用EnumSet和forEach
EnumSet.allOf(Direction.class).forEach(...);
使用数组。asList with forEach
Arrays.asList(Direction.values()).forEach(...);
你可以这样做:
for (Direction direction : EnumSet.allOf(Direction.class)) {
// do stuff
}
我们可以像这样使用一个过滤器(JAVA 8)。
Stream.of(Direction.values()).filter(name -> !name.toString().startsWith("S")).forEach(System.out::println);
如果你不关心顺序,这应该工作:
Set<Direction> directions = EnumSet.allOf(Direction.class);
for(Direction direction : directions) {
// do stuff
}