首页 > 解决方案 > 在 Java 中组织、实现和查询数据结构类

问题描述

我正在自学用 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;
    }
}

我想帮助我学习如何实现这种数据结构。先感谢您!

标签: javadata-structureshashmap

解决方案


你应该软化你的逻辑:

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())); 
    }

您只需要传递 aPredicate<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);
});

推荐阅读