Reputation: 658
In my database I have a table which is show in below. Now I want to make a nested data structure to draw on a view by an algorithm to transfer data from table to this
Tables -> Seats -> Rounds -> Dish_names
Note that -> stands for 'contain'
Could anyone have a clean way to do this in Java. Thanks!
Upvotes: 3
Views: 253
Reputation: 109613
The class structure as you mentioned.
class Table
List<Seat> seats = ArrayList<>();
class Seat
List<Round> rounds = ArrayList<>();
class Round
List<Seat> seats = ArrayList<>();
class Dish
For instance, using immutable objects:
public class Table {
public final int id;
public final List<Seat> seats = ArrayList<>();
public Table(int id) {
this.id = id;
}
}
For construction of unique entity objects you need to map the keys to the entity object.
Map<Integer, Table> tablesById = new HashMap<>();
Map<Integer, Seat> seatsById = new HashMap<>();
Map<Integer, Round> roundsById = new HashMap<>();
Map<String, Dish> dishesByName = new HashMap<>();
With a bit more effort, but cleaner result one could make
Set<Table>
etcetera.
Now you can traverse the database table and check
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);
...
The method putIfAbsent
exists since java 8. In earlier java you can get
and only when it does not exist put
a new Table.
Upvotes: 0
Reputation: 1567
Not sure what you want exactly, but if you want a nested Java Object (entity) to correspond to the table, read on:
Since Tables contain Seats contain Rounds contain Dish_names, you start from the innermost entity (Dish):
Public class Dish{
private int id; // an id
private String dish_name;
// getters and setters
}
Your Round
s contain the Dish
es
Public class Round{
private int id; // an id
private List<Dish> dishes;
// getters and setters
}
Your Seat
s contain the Round
s
Public class Seat{
private int id; // an id
private List<Round> rounds;
// getters and setters
}
And finally you Table
s contain the Seat
s
Public class Table{
private int id; //
private List<Seat> seats;
// getters and setters
}
Upvotes: 1