Atul Kumar Verma
Atul Kumar Verma

Reputation: 369

Check if a list of Enums contains a String in Java

I have a list of objects with one attribute type. I want to filter that list to contain only those objects whose value is in the list of Enum.

Here is a simple version of Java Program describing above.

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(p.getType())) {
       System.out.println("Player type is : " + p.getType());
    }
}

I want to retain only those items in the players List which are part of enum list. Above does not seem to work. Please suggest a way to achieve this. I am doing this in Java 8.

Upvotes: 0

Views: 6427

Answers (3)

Alain Cruz
Alain Cruz

Reputation: 5097

If you want to find if an Enum has a String, I would add a Hashmap to our Enum and add our value as a key. This way, I can do a simple get and check if it exists.

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;
    }

}

Then, all you would need to do is check if the String exists using the containsString method of our Enum.

Player player = new Player("FAST");
if(PlayerSpeed.constainsString(p.getType())) {
   System.out.println("Player type is : " + p.getType());
}

I already tried this code and it is working like intended. Please let me know if it helps.

Upvotes: 0

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147154

You enum doesn't even compile. Once you've got a minimal complete example that otherwise works, you just need to use 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);
   }
}

Update: Original poster has said Player stores type in a String (for whatever reason). So that'll need to be looked up to the enum type (or just use a Set<String> playerTypes).

   myPlayers.removeIf(player -> 
       !playerTypes.contains(PlayerType.valueOf(player.type()))
   );

Upvotes: 0

Apoorv Agarwal
Apoorv Agarwal

Reputation: 336

According to me, there are two ways:

*Instead of creating the list of player types with enums, use enum names:

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());
    }
}

*You can use the valueOf method of the enum class to convert the string obtained from p.getType() into an Enum:

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());
    }
}

Upvotes: 1

Related Questions