lukasz-p
lukasz-p

Reputation: 183

Map multiple rows to one object based on column value

In my system I have user_transactions table, it contains id, transaction_type, transaction_date, linked_transaction columns. At the beginning of a shift, the system creates transaction START_SHIFT in db, and at the end a new transaction called END_SHIFT with START_SHIFT transaction id in the linked_transaciton column. Right now I need to take out all start_shift and end_shift transactions and map them to session object with fields: id, startDate, endDate id should be start_shift transaction id, startDate is START_SHIFT transaction date and endDate is END_SHIFT transaction date. For now, I take these two types of transactions from db as a list of transactions, I create an object for every START_SHIFT transaction and I add them to the list but I don't know how to set endDate in these objects

        List<TerminalSession> userSessions = new ArrayList<>();

        transactions.stream().filter(t -> t.getType().equals(TransactionType.START_SHIFT)).forEach(t -> {
            UserSession userSession = new UserSession();
            userSession.setId(Long.getLong(t.getId()));
            userSession.setStartDate(t.getTransactionDate());
            userSessions.add(userSession);
        }); ```

Upvotes: 0

Views: 577

Answers (1)

Loris Securo
Loris Securo

Reputation: 7638

Since it's the END_SHIFT transaction that has the link to its corresponding START_SHIFT transaction, you probably could start from them to create the session objects.

To retrieve the START_SHIFT transaction from the END_SHIFT linked transaction id you could prepare a map with the id as the key:

Map<Long, Transaction> map = transactions.stream()
            .collect(Collectors.toMap(Transaction::getId, Function.identity()));

transactions.stream()
    // END_SHIFT instead of START_SHIFT
    .filter(t -> t.getType().equals(TransactionType.END_SHIFT))  
    .forEach(t -> {
        UserSession userSession = new UserSession();

        // get id and start date from the linked START_SHIFT in the map
        Transaction startShift = map.get(t.getLinkedTransaction());
        userSession.setId(startShift.getId());
        userSession.setStartDate(startShift.getTransactionDate());

        userSession.setEndDate(t.getTransactionDate());
        userSessions.add(userSession);
    });

Upvotes: 1

Related Questions