Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate Set of Integers through HashSet using Java Streams

I was trying to create a HashSet by get all keys of a HashMap whose values are greater than 0. To do so, i considered Java Streams, something with Collectors, but without success. The only way i got success was using a forEach loop with an if statement inside, described in the code below:

HashMap<Integer, Double> profiencyOnSkill;
HashSet<Integer> skills;

profiencyOnSkill.put(1, 0.5);
profiencyOnSkill.put(2, 0.0);
profiencyOnSkill.put(3, 1.0);
profiencyOnSkill.put(4, 0.02);
profiencyOnSkill.put(5, 0.0);

profiencyOnSkill
            .entrySet()
            .stream()
            .forEach(pair -> {
                if (pair.getValue() > 0.0) {
                    skills.add(pair.getKey());
                }
            });

skills.forEach(System.out::println);

Is there any direct way to do with Collectors? All my ideas with Collectors returned a Map.Entry<Integer, Double>. Something like that:

Set<Map.Entry<Integer, Double>> someSet = proficiencyOnSkill.entrySet().stream().filter(x-> x.getValue() == 2).collect(Collectors.toSet());
like image 890
José Joaquim Avatar asked Jun 03 '26 15:06

José Joaquim


2 Answers

Note that if you don’t need the original mappings afterwards, you can also do

HashMap<Integer, Double> profiencyOnSkill = …;
profiencyOnSkill.values().removeIf(v -> v<=0);
Set<Integer> skills = profiencyOnSkill.keys();

skills.forEach(System.out::println);
like image 126
Holger Avatar answered Jun 06 '26 04:06

Holger


Please initialize your types so your code is runnable. Anyway, yes you can filter on your criteria then map on the Entry.key and collect to a Set like

Map<Integer, Double> profiencyOnSkill = new HashMap<>();

profiencyOnSkill.put(1, 0.5);
profiencyOnSkill.put(2, 0.0);
profiencyOnSkill.put(3, 1.0);
profiencyOnSkill.put(4, 0.02);
profiencyOnSkill.put(5, 0.0);
Set<Integer> skills = profiencyOnSkill.entrySet().stream()
        .filter(pair -> pair.getValue() > 0)
        .map(Entry::getKey).collect(Collectors.toSet());

And you could (but don't have to) just print skills.

System.out.println(skills);

I get

[1, 3, 4]
like image 43
Elliott Frisch Avatar answered Jun 06 '26 04:06

Elliott Frisch



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!