Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Array and copying it into a List

To be clear I don't have any problems and don't really need help but I wanted to ask anyway:

Let's say we have a String array

String[] sarr = new String[]{"POTATO", "TOMATO"};

and we have an enum

public enum Food{POTATO, TOMATO, PIZZA}

If I wanted to check if all Strings in sarr are present in Food, I'd do the following:

ArrayList<String> foodstrings = new ArrayList<>();
Arrays.asList(Food.values()).forEach((in) -> foodstrings.add(in.toString()));
if (!foodstrings.containsAll(Arrays.asList(sarr))) doStuff();

Is there a way to do this in less lines of code? Or simply a more elegant way?

like image 205
Nicolas Torres Avatar asked May 05 '26 03:05

Nicolas Torres


2 Answers

You want to determine if all element in your array are contained in the list of food names.

A possible solution is to convert the food names to a Set (to have a O(1) contains); then, we need to determine if all elements in the array are contained in this set:

public static void main(String[] args) {
    String[] sarr = new String[]{"POTATO", "TOMATO"};
    Set<String> set = Arrays.stream(Food.values()).map(Enum::name).collect(Collectors.toSet());
    boolean result = Arrays.stream(sarr).allMatch(set::contains);
}

In your current solution, you are mutating an external variable with forEach, which is a bad practice.

like image 53
Tunaki Avatar answered May 08 '26 05:05

Tunaki


I believe a better version of the first two lines would be:

Set<String> foodstrings = Arrays.stream(Food.values()).map(Enum::name).collect(Collectors.toSet());

Using Set instead of List will improve performance of containsAll, and the code is entirely streamed, instead of using forEach and an external collector.

The if is still good, although you could just combine it all into a single statement (formatted for readability):

if (! Arrays.stream(Food.values())
            .map(Enum::name)
            .collect(Collectors.toSet())
            .containsAll(Arrays.asList(sarr))) {
    doStuff();
}
like image 36
Andreas Avatar answered May 08 '26 03:05

Andreas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!