Check if a string is startwith in an array

String[] directions = {"UP","DOWN","RIGHT","LEFT"};
String input = "DOWN 123 test";

Is there a way to check the input string is startwith one value in directions without using split input value?

Jon Skeet
people
quotationmark

Sure - just iterate over all the directions:

private static final String[] DIRECTIONS = {"UP","DOWN","RIGHT","LEFT"};

public static String getDirectionPrefix(String input) {
    for (String direction : DIRECTIONS) {
        if (input.startsWith(direction)) {
            return direction;
        }
    }
    return null;
}

Or using Java 8's streams:

private static final List<String> DIRECTIONS = Arrays.asList("UP","DOWN","RIGHT","LEFT");

public static Optional<String> getDirectionPrefix(String input) {
    return DIRECTIONS.stream().filter(d -> input.startsWith(d)).findFirst();
}

people

See more on this question at Stackoverflow