Is there a performance advantage when using Arrays.stream () to iterate over an array?

I need to repeat all the enumeration values, check if they were used to build int (called input), and if so, add them to Set (called usefulEnums). I can use the thread API or iterate over all the enumerations to complete this task. Is there any benefit to using Arrays.stream()compared to the traditional approach to iterating over an array values()?

   enum TestEnum { VALUE1, VALUE2, VALUE3 };

   Set<TestEnum> usefulEnums = new HashSet<>();

   Arrays.stream(TestEnum.values())
            .filter(t -> (input & t.getValue()) != 0)
            .forEach(usefulEnums::add);

    for (TestEnum t : TestEnum.values()) {
        if ((input & t.getValue()) != 0) {
            usefulEnums.add(t);
        }
    }
+4
source share
2 answers

for loop ( ), more verbose, , . .

, HashSet:

Arrays.stream(TestEnum.values())
        .filter(t -> (input & t.getValue()) != 0)
        .collect(Collectors.toCollection(HashSet::new));

, , :

EnumSet<TestEnum> filtered = EnumSet.allOf(TestEnum.class).stream()
            .filter(t -> (input & t.getValue()) != 0)
            .collect(Collectors.toCollection(() -> EnumSet.noneOf(TestEnum.class)));
+2

, :

Set<TestEnum> usefulEnums = EnumSet.allOf(TestEnum.class);
usefulEnums.removeIf(t -> (input & t.getValue()) == 0);

, enum , EnumSet.allOf(EnumType.class).stream() EnumType.values(), , enum , . , JVMs .

, Set<TestEnum>, EnumSet HashSet , Set. EnumSet, , , long 0b111, .

+3

Source: https://habr.com/ru/post/1670717/


All Articles