Java中用于制作嵌套数据结构的算法

3

在我的数据库中,有一张如下所示的表。现在我想通过算法将数据从表格转换为嵌套数据结构,以便在视图上进行绘制。

Tables -> Seats -> Rounds -> Dish_names

Note that -> stands for 'contain'

有没有一种干净的方法在Java中做到这一点。谢谢!

在此输入图片描述

2个回答

1

我不确定你确切想要什么,但如果你想让嵌套的Java对象(实体)对应于表格,请继续阅读:

由于表格包含座位包含轮次包含菜名,因此您从最内部的实体(菜品)开始:

Public class Dish{
  private int id; // an id  
  private String dish_name;
  // getters and setters
}

你的Round包含了Dish

 Public class Round{
      private int id; // an id  
      private List<Dish> dishes;
      // getters and setters
    }

您的座位包含圆形。
Public class Seat{
      private int id; // an id  
      private List<Round> rounds;
      // getters and setters
    }

最后,您的表格包含座位。
 Public class Table{
      private int id; //  
      private List<Seat> seats;
      // getters and setters
    }

是的,那些是实体,但我需要从表格中填写数据。 - Kevin Duong

0
你所提到的是类结构。
class Table
    List<Seat> seats = ArrayList<>();

class Seat
    List<Round> rounds = ArrayList<>();

class Round
    List<Seat> seats = ArrayList<>();

class Dish

例如,使用不可变对象:
public class Table {
    public final int id;
    public final List<Seat> seats = ArrayList<>();

    public Table(int id) {
        this.id = id;
    }
}

为构建唯一实体对象,您需要将键映射到实体对象。

Map<Integer, Table> tablesById = new HashMap<>();
Map<Integer, Seat> seatsById = new HashMap<>();
Map<Integer, Round> roundsById = new HashMap<>();
Map<String, Dish> dishesByName = new HashMap<>();

稍微花费一些努力,但结果更加干净的方法是可以创建“Set<Table>”等。 现在您可以遍历数据库表并检查。
Table table = new Table(resultSet.getInt("Table"));
table = tablesById.putIfAbsent(table.id, table);
// Now table is a maybe already existing table of the map.

Seat seat = new Table(resultSet.getInt("Seat"));
seat = seatsById.putIfAbsent(seat.id, seat);
table.seats.add(seat);

...

putIfAbsent 方法自 Java 8 开始存在。在早期的 Java 中,您可以使用 get 方法,只有当它不存在时才能 put 一个新表。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接