Java 如何在不打印重复项的情况下打印HashMap中的值?

Java 如何在不打印重复项的情况下打印HashMap中的值?,java,printing,hashmap,Java,Printing,Hashmap,我正在尝试修复这段代码,其中我从一个hashmap打印,该hashmap有一个车牌号列表和该格式的所有者。我试图通过printOwners打印出所有者;但我不能让它不打印副本 我已经玩了一段时间了,只是不能跳过重复的 这是我的密码: import java.util.ArrayList; import java.util.HashMap; public class VehicleRegister { private HashMap<RegistrationPlate, Stri

我正在尝试修复这段代码,其中我从一个hashmap打印,该hashmap有一个车牌号列表和该格式的所有者。我试图通过printOwners打印出所有者;但我不能让它不打印副本

我已经玩了一段时间了,只是不能跳过重复的

这是我的密码:

import java.util.ArrayList;
import java.util.HashMap;

public class VehicleRegister {

    private HashMap<RegistrationPlate, String> owners;

    public VehicleRegister() {
        owners = new HashMap<RegistrationPlate, String>();
    }

    public boolean add(RegistrationPlate plate, String owner) {
        //search for existing plate
        if (!(owners.containsKey(plate))) { // add if no plate
            owners.put(plate, owner);
            return true;
        }

        //if plate is found, check for owner
        else if (owners.keySet().equals(owner)) {
           return false;
        }

        return false;
    }

    public String get(RegistrationPlate plate) {
        return owners.get(plate);
    }

    public boolean delete(RegistrationPlate plate) {
        if (owners.containsKey(plate)) {
            owners.remove(plate);
            return true;
        }

        return false; 
    }

    public void printRegistrationPlates() {
        for (RegistrationPlate item : owners.keySet()) {
            System.out.println(item);
        }
    }

    public void printOwners() {

        for (RegistrationPlate item : owners.keySet()) {
            System.out.println(owners.get(item));            
        }
    }
}

要删除重复项,请使用:


对不起,我是新来的。这是因为新哈希集的打印只会打印一个不重复的密钥吗?你能解释一下吗,如果你愿意的话,我是Java新手,只是在学习散列。另外,谢谢你的回答。我可以将它发送到arraylist并从那里打印,但我想知道是否有更简单的方法。在Java中,HashSet实现的集合结构不包含重复项:如果一个元素被多次添加到集合中,那么其中实际上只包含一个。使用Set通常是从其他集合中删除重复项的方法,例如可以多次包含同一元素的列表。啊,一行代码将是一个非常简单的解决方案!
public void printOwners() {
    for (String s : new HashSet<>(owners.values())) {
        System.out.println(s);            
    }
}
public void printOwners() {
    owners.values().stream().distinct().forEach(System.out::println);
}