javasetenum-map

EnumMap<Object,Set<x>> - how to have unique values for every key


I'm trying to make something like this.

Let's say my EnumMap looks like this EnumMap<Animals, Set<Integer>>. I have keys like: Dog,Fish,Cat from Animals class. And I want to print all values from Animals Dog, Fish and Cat.

As you can see, Cat has 2 from Dog, and 5 from Fish. So the output will be: 1,2,3,4,5,6,2,5,7.

I want to remove duplicates during adding process to EnumMap.

So it should be like: 1,2,3,4,5,6,7. I cannot filter later after adding all values. How can I do this?


Solution

  • This should help:

    public class Test {
    
        private Map<Animal, Set<Integer>> m = new EnumMap<>(Animal.class);
    
        public Test() {
            m.put(Animal.DOG, Set.of(1, 2, 3));
            m.put(Animal.FISH, Set.of(4, 5, 6));
        }
    
        public static void main(String[] args) {
            Test t = new Test();
            t.addValueIfNotPresent(Animal.CAT, 2);
            t.addValueIfNotPresent(Animal.CAT, 5);
            t.addValueIfNotPresent(Animal.CAT, 7);
    
            System.out.println(t.m);
        }
    
        private void addValueIfNotPresent(Animal key, Integer value) {
            if (m.values().stream().flatMap(Collection::stream).noneMatch(value::equals)) {
                m.compute(key, (animal, integers) -> {
                    if (Objects.isNull(integers)) {
                        Set<Integer> s = new HashSet<>();
                        s.add(value);
                        return s;
                    } else {
                        integers.add(value);
                        return integers;
                    }
                });
            }
        }
    
        enum Animal {DOG, CAT, FISH}
    }
    

    Output:

    {DOG=[3, 2, 1], CAT=[7], FISH=[4, 6, 5]}
    

    This is not very optimized and clean, but should give you an idea on how to proceed.