如何在不打印重复项的同时从 HashMap 打印值?

How would I print values from a HashMap while not printing duplicates?(如何在不打印重复项的同时从 HashMap 打印值?)
本文介绍了如何在不打印重复项的同时从 HashMap 打印值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在尝试修复这段代码,我正在从具有车牌号和所有者列表(该格式)的哈希图中打印.我试图通过 printOwners(); 打印出所有者.但我不能让它不打印重复.

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 via printOwners(); but I can't get it to not print duplicates.

我已经玩了一段时间了,似乎无法跳过重复项.

I've played around with it for a while, just can't seem to skip over duplicates.

这是我的代码:

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:

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

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

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

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

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

这篇关于如何在不打印重复项的同时从 HashMap 打印值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Show progress during FTP file upload in a java applet(在 Java 小程序中显示 FTP 文件上传期间的进度)
How to copy a file on the FTP server to a directory on the same server in Java?(java - 如何将FTP服务器上的文件复制到Java中同一服务器上的目录?)
FTP zip upload is corrupted sometimes(FTP zip 上传有时会损坏)
Enable logging in Apache Commons Net for FTP protocol(在 Apache Commons Net 中为 FTP 协议启用日志记录)
Checking file existence on FTP server(检查 FTP 服务器上的文件是否存在)
FtpClient storeFile always return False(FtpClient storeFile 总是返回 False)