From 3ae82245ee9558562ca334d95dc0ee392e643f3d Mon Sep 17 00:00:00 2001 From: DiegoMarti2 <150871541+DiegoMarti2@users.noreply.github.com> Date: Tue, 2 Jan 2024 16:16:26 +0200 Subject: [PATCH] BAEL-7041 Commit for the article "Check if List Contains At Least One Enum" which adds the "CheckIfListContainsEnumUnitTest" class to check if a list contains an enum in Java. --- .../CheckIfListContainsEnumUnitTest.java | 76 +++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 core-java-modules/core-java-collections-5/src/test/java/com/baeldung/checkiflistcontainsenum/CheckIfListContainsEnumUnitTest.java diff --git a/core-java-modules/core-java-collections-5/src/test/java/com/baeldung/checkiflistcontainsenum/CheckIfListContainsEnumUnitTest.java b/core-java-modules/core-java-collections-5/src/test/java/com/baeldung/checkiflistcontainsenum/CheckIfListContainsEnumUnitTest.java new file mode 100644 index 0000000000..c92e7264bb --- /dev/null +++ b/core-java-modules/core-java-collections-5/src/test/java/com/baeldung/checkiflistcontainsenum/CheckIfListContainsEnumUnitTest.java @@ -0,0 +1,76 @@ +package com.baeldung.checkiflistcontainsenum; + +import java.util.*; + +import org.junit.Assert; +import org.junit.Test; + +public class CheckIfListContainsEnumUnitTest { + private final List> data = new ArrayList<>(); + public boolean containsDeveloper = false; + List list = Arrays.asList(Position.values()); + + public CheckIfListContainsEnumUnitTest() { + Map map = new HashMap<>(); + map.put("Name", "John"); + map.put("Age", 25); + map.put("Position", Position.DEVELOPER); + + data.add(map); + } + + + @Test + public void givenDataList_whenUsingLoop_thenCheckIfListContainsEnum() { + for (Map entry : data) { + Object positionValue = entry.get("Position"); + + for (Position position : Position.values()) { + if (positionValue.equals(position)) { + containsDeveloper = true; + break; + } + } + + if (containsDeveloper) { + break; + } + } + + Assert.assertTrue(containsDeveloper); + } + + @Test + public void givenDataList_whenUsingStream_thenCheckIfListContainsEnum() { + containsDeveloper = data.stream() + .map(entry -> entry.get("Position")) + .anyMatch(position -> Arrays.asList(Position.values()).contains(position)); + + Assert.assertTrue(containsDeveloper); + } + + @Test + public void givenDataList_whenUsingDisjointMethod_thenCheckIfListContainsEnum() { + List positionValues = data.stream() + .map(entry -> (Position) entry.get("Position")) + .toList(); + + boolean containsDeveloper = !Collections.disjoint(list, positionValues); + Assert.assertTrue(containsDeveloper); + } + + + public enum Position { + DEVELOPER("Dev"), MANAGER("Mgr"), ANALYST("Analyst"); + + private final String value; + + Position(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + } +}