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.
Here is my code:
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));
}
}
}
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.