3 回答
TA贡献1789条经验 获得超8个赞
在我看来,有两种方式:
*不要使用枚举创建玩家类型列表,而是使用枚举名称:
public enum Types {
SLOW("Slow"), FAST("Fast"), VERY_FAST("Running");
}
List<String> playerTypes = new ArrayList<>();
playerTypes.add(Types.SLOW.name());
List<Player> myPlayers = new ArrayList<>();
Player player = new Player("FAST");
myPlayers.add(player);
for (Player p : myPlayers) {
if(playerTypes.contains(p.getType())) {
System.out.println("Player type is : " + p.getType());
}
}
*您可以使用valueOf枚举类的方法将获取的字符串p.getType()转换为枚举:
public enum Types {
SLOW("Slow"), FAST("Fast"), VERY_FAST("Running");
}
List<Types> playerTypes = new ArrayList<>();
playerTypes.add(Types.SLOW);
List<Player> myPlayers = new ArrayList<>();
Player player = new Player("FAST");
myPlayers.add(player);
for (Player p : myPlayers) {
if(playerTypes.contains(Types.valueOf(p.getType()))) {
System.out.println("Player type is : " + p.getType());
}
}
TA贡献1810条经验 获得超5个赞
如果你想知道一个 Enum 是否有一个 String,我会向我们的 Enum 添加一个 Hashmap 并将我们的值添加为一个键。这样,我可以做一个简单的获取并检查它是否存在。
public enum PlayerSpeed {
// Type of speeds.
SLOW("Slow"),
FAST("Fast"),
VERY_FAST("Running");
// String value that represents each type of speed.
public final String value;
// Hash map that let us get a speed type by it's String value.
private static Map map = new HashMap<>();
// Private constructor.
private PlayerSpeed(String value) { this.value = value; }
// Fill our hash map.
static {
for (PlayerSpeed playerSpeed : PlayerSpeed.values()) {
map.put(playerSpeed.value, playerSpeed);
}
}
/**
* Given a string, look it up in our enum map and check if it exists.
* @param searchedString String that we are looking for.
* @return True if the string is found.
*/
public static boolean containsString(String searchedString) {
return map.get(searchedString) != null;
}
}
然后,您需要做的就是使用 Enum 的 containsString 方法检查 String 是否存在。
Player player = new Player("FAST");
if(PlayerSpeed.constainsString(p.getType())) {
System.out.println("Player type is : " + p.getType());
}
我已经尝试过这段代码,它按预期工作。如果有帮助,请告诉我。
TA贡献1863条经验 获得超2个赞
你枚举甚至不编译。一旦您获得了一个可以正常工作的最小完整示例,您只需要使用Collections.removeIf.
import java.util.*;
import java.util.stream.*;
enum PlayerType {
SLOW, FAST, VERY_FAST
}
class Player {
private final PlayerType type;
public Player(PlayerType type) {
this.type = type;
}
public PlayerType type() {
return type;
}
@Override public String toString() {
return type.name();
}
}
interface Play {
static void main(String[] args) {
Set<PlayerType> playerTypes = EnumSet.of(
PlayerType.SLOW
);
List<Player> myPlayers = new ArrayList<>(Arrays.asList(
new Player(PlayerType.FAST)
));
myPlayers.removeIf(player -> !playerTypes.contains(player.type()));
System.err.println(myPlayers);
}
}
更新:原始海报说Player商店输入 a String(无论出于何种原因)。因此,需要查找枚举类型(或仅使用 a Set<String> playerTypes)。
myPlayers.removeIf(player ->
!playerTypes.contains(PlayerType.valueOf(player.type()))
);
添加回答
举报