How would I print values from a HashMap while not printing duplicates?

后端 未结 1 1967
傲寒
傲寒 2021-01-07 05:30

I\'m trying to fix this piece of code where I\'m printing from a hashmap having a list of plate numbers and owners (that format). I\'m trying to print out just the owners

相关标签:
1条回答
  • 2021-01-07 05:53

    To remove the duplicates, use a HashSet<String>:

    public void printOwners() {
        for (String s : new HashSet<>(owners.values())) {
            System.out.println(s);            
        }
    }
    

    Alternatively with Java 8 Stream and the distinct() method:

    public void printOwners() {
        owners.values().stream().distinct().forEach(System.out::println);
    }
    
    0 讨论(0)
提交回复
热议问题