Kevin Duong
Kevin Duong

Reputation: 658

Algorithm to make nested data structure from a table in Java

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!

enter image description here

Upvotes: 3

Views: 253

Answers (2)

Joop Eggen
Joop Eggen

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

jmcg
jmcg

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 Rounds contain the Dishes

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

Your Seats contain the Rounds

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

And finally you Tables contain the Seats

 Public class Table{
      private int id; //  
      private List<Seat> seats;
      // getters and setters
    }

Upvotes: 1

Related Questions