Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to use Java8 streams to implement this collection

private enum EnumVals {
        FIRST(new String[]{"a","b"}),
        SECOND(new String[]{"a","b","c","d"}),
          THIRD(new String[]{"d","e"});

        private String[] vals;

        EnumVals(String[] q) {
            vals=q;
        }

        public String[] getValues(){
            return vals;
        }
    };

What I need is the unique combined list of all EnumVals.getValues().

String[] allVals = {"a","b","c","d","e"}

I did something like below, but it throws error :

Stream.of(EnumVals.values()).map(w->w.getValues()).collect(Collectors.toCollection(HashSet::new)).toArray(new String[0]);
like image 525
Zenil Avatar asked Dec 02 '25 13:12

Zenil


1 Answers

You need to use flatMap to flatten the arrays. Additionally, you can use distinct() on the stream instead of collecting into a HashSet.

Arrays.stream(EnumVals.values())
    .map(EnumVals::getValues)
    .flatMap(Arrays::stream)
    .distinct()
    .toArray(String[]::new);
like image 159
Misha Avatar answered Dec 05 '25 04:12

Misha



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!