【问题标题】:Create a class structure based on map with composite key and value使用复合键和值创建基于映射的类结构
【发布时间】:2017-11-19 07:22:49
【问题描述】:

我有一张地图:

Map<Map<String,Map>, List<Map<String, String>>> map = new HashMap();

使用 OOP 原则重构以下数据结构并创建类结构的最简单方法是什么?

【问题讨论】:

  • 你能解释一下你想要达到的目标吗?

标签: java dictionary hashmap


【解决方案1】:

在开始重构之前,您应该对想要实现的目标有一个简单而清晰的了解:

  1. 您能否将集合中的数据分解为业务实体(订单、产品、客户等)?

  2. 这些数据之间的关系是什么?它可以是链接到包含产品的订单的用户列表。

  3. 将正确的集合用于正确的用途。 HashMap 是键/值对无序集合。您可以通过键访问元素(一个键指向一个值,没有重复的键)。 ArrayList 是仅有序集合的值。您可以通过整数索引访问元素。

给定以下集合:

HashMap<String, HashMap<String, String>> map = new HashMap<String, HashMap<String, String>>();

及其表示:

{
  "Order-Ref-01": {
     "id": "123456"
     "client": "MrFooBar"
     "destination": "USA"
     "type": "Electronic"
  },
  "Order-Ref-02": {
    //...
  } 
}

您可以将其重构为订单列表,因为您决定例如不需要按键获取。

List<Order> orders = new ArrayList<>();

您可以创建 2 个以上的类作为业务实体:

class Client {
  private String id;
  private String name;
  // ...
}

class Order {
  private String id;
  private Client client;
  private String destination;
  private String type;
  // ...
}

这一切都是为了将​​您的数据结构分解为代表您的业务实体及其关系的较小部分。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-23
    • 2010-09-09
    • 2012-05-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多