java - 如何打印 HashMap 中的值而不打印重复项?

标签 java printing 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));            
        }
    }
}

最佳答案

要删除重复项,请使用 HashSet<String> :

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

或者使用 Java 8 Streamdistinct()方法:

public void printOwners() {
    owners.values().stream().distinct().forEach(System.out::println);
}

关于java - 如何打印 HashMap 中的值而不打印重复项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32109112/

相关文章:

java - 使用 java applet 在打印机中打印渲染的网页

php - 为什么我不能使用 CSS 更改显示状态?

java - 通过 HashMap 坐标搜索

java - for循环很慢

java - Dockerizing 使用 oracle-ojdbc : How do you get the driver in there? 的 Maven 应用程序

java - 如何在Windows机器上动态定位jjs.exe?

c - 试图让这个显示功能起作用

java HashMap 排序 <String,Integer> 。如何排序?

java - 在 Swing 应用程序中运行 SWT 组件

java - 将 Single<List<Item>> 转换为 Observable<Item>?