我正在教我自己用Java编码。我是一个初学者,但对编程并非完全一无所知。我决定为计算机维修店制作一个跟踪票证、客户和设备的应用程序。我已经为该应用程序编写了"大量"代码,但正如我所说,我是一个初学者,我不知道什么是实现应用程序数据结构的"正确方法"(最好、最聪明和方便(。
我决定使用自定义数据类,这些类是带有整数键的 HashMap 中的值对象,并且表示镜像数据库中数据表的数据表。我做错了吗?
public class Clients
{
private String firstName;
private String lastName;
private String primePhoneNum;
private String secondPhoneNum;
private String email;
private String address;
private MarketingTypes marketing;
//getters and setters
}
public HashMap<Integer,Clients> clientsTable = new HashMap<Integer, Clients>();
当我尝试使搜索函数根据该对象特定字段值在 HashMap 中返回值对象时,我遇到了麻烦。例如:
public class SearchDeviceTypes
{
private Map<Integer, DeviceTypes> deviceTypesTable;
public SearchDeviceTypes(Map<Integer, DeviceTypes> deviceTypesTable)
{
this.deviceTypesTable = deviceTypesTable;
}
public boolean isNameTaken(String name)
{
return deviceTypesTable.entrySet().stream()
.anyMatch(deviceType->deviceType.getValue().getName().equals(name));
}
public DeviceTypes getByID(int id)
{
return deviceTypesTable.get(id);
}
public Map<Integer, DeviceTypes> filterByName(String text)
{
return deviceTypesTable.entrySet().stream()
.filter(deviceType->deviceType.getValue().getName().contains(text))
.collect(Collectors.toMap(deviceType -> deviceType.getKey(), deviceType -> deviceType.getValue()));
}
public DeviceTypes getByName(String name)
{
//How to implement this?
return null;
}
}
我想帮助我学习如何实现这种数据结构。提前谢谢你!
你应该软化你的逻辑:
public Map<Integer, DeviceTypes> filterByName(String text)
{
return deviceTypesTable.entrySet().stream()
.filter(deviceType->deviceType.getValue().getName().contains(text))
.collect(Collectors.toMap(deviceType -> deviceType.getKey(), deviceType -> deviceType.getValue()));
}
您只需要传递一个Predicate<DeviceType>
,而不是使用.getName().contains(text)
对逻辑进行硬编码:
public Map<Integer, DeviceType> filterBy(Predicate<DeviceType> predicate) {
Objects.requireNonNull(predicate, "predicate");
return deviceTypesTable.entrySet().stream()
.filter(entry -> predicate.test(entry.getValue())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}
但是,您可以为其别名:
public Map<Integer, DeviceType> filterByName(String name) {
Objects.requireNonNull(name, "name");
return filterBy(dt -> dt.getName().contains(name));
}
由于你想要一个DeviceType
,这给了:
public Optional<DeviceType> findFirst(Predicate<DeviceType> predicate) {
Objects.requireNonNull(predicate, "predicate");
return deviceTypesTable.values().stream()
.filter(predicate)
.findFirst();
}
该方法将返回与谓词匹配的第一个DeviceType
,例如:
allDevices.findFirst(dt -> "disk".equalsIgnoreCase(dt.name)).ifPresent(dt -> {
System.out.println("deviceType: " + dt);
});
如果我很了解你,你只需要在你的类客户端中放置一个 ID 参数。 您不需要仅为标识符创建结构。