J
J
Jake Taylor2021-11-03 14:25:43
Java
Jake Taylor, 2021-11-03 14:25:43

How to get the object from the previous step in Stream?

There is a method in the DAO layer. In the method, a request is made with help CriteriaBuilder. This method receives as an argument Map<ColumnName, SqlSortOperator> params:

@Override
    public Set<GiftCertificate> findAllOrderBy(Map<ColumnName, SqlSortOperator> params) {
        CriteriaBuilder cb = entityManager.getCriteriaBuilder();
        CriteriaQuery<GiftCertificate> cq = cb.createQuery(GiftCertificate.class);
        Root<GiftCertificate> from = cq.from(GiftCertificate.class);
        // work with Stream....
}


Made it work with the Mapfollowing:
Set<Order> orders = new HashSet<>();        
for(Map.Entry<ColumnName, SqlSortOperator> entry : params.entrySet()) {
    String field = entry.getKey().name().toLowerCase();
    Path<String> path = from.get(field);

    SqlSortOperator sqlSortOperator = entry.getValue();
    Order order = sqlSortOperator.equals(SqlSortOperator.ASC) ? cb.asc(path) : cb.desc(path);            
    orderSet.add(order);
}


It looks cumbersome, I decided to rewrite using Stream, but ran into a moment - How to get an object from the previous step in a Stream:
Set<Order> orders = params.entrySet().stream()
                .map(Map.Entry::getKey)
                .map(Enum::name)
                .map(String::toLowerCase)   // String columnName = "name"
                .map(from::get) // Path<String> path = from.get(columnName);
                .map() // Как выполнить SqlSortOperator sqlSortOperator = entry.getValue();
                .map() // Order order = sqlSortOperator.equals(SqlSortOperator.ASC) ? cb.asc(path) : cb.desc(path); 
                .collect(Collectors.toSet());

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
Jake Taylor, 2021-11-13
@n199a

Here is an example. You can get an object from any previous step. To do this, you need to open a new one Stream.of()inside the current stream:

return orderDao.findUsersWithHighestCostOfAllOrders().stream()
                .flatMap(up -> Stream.of(up)
                        .map(UserPrice::getUser)
                        .map(this::findAllGiftCertificatesByUser)
                        .map(this::findAllTagsFromGiftCertificates)
                        .map(this::findCountOfRepetitionsOfEachTag)
                        .map(map -> buildMostWidelyUsedTag(up, map)))
                .collect(Collectors.toSet());

D
Dmitry Roo, 2021-11-03
@xez

No way. We must look for another solution.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question