Simplifying/Migrating Source Code method to Java 8

Viewed 30

I have been attempting to convert this source code to be conventionally formatted using Java 8. I have been following a few conversion guides but haven't been able to get any solutions working. What am I doing wrong?

Here is the source code:

private List<ResponseVo> populateResponse(String userId, String type) {

    List<Wrapper> recordsList = logRepo.getEntities(type, userId);
    List<ResponseVo> responseVoList = new ArrayList<>();

    if (null != userId) {
        for (Wrapper record : recordsList) {
            if (record.getSortKey().contains(userId)) {
                ResponseVo responseVo = buildResultsResponse(record);
                responseVoList.add(responseVo);
            }
        }
    } else {
        for (Wrapper record : recordsList) {
            ResponseVo testLogResponseVo = buildResultsResponse(record);
            responseVoList.add(responseVo);
        }
    }
    return responseVoList;
}

I have attempted using the Collectors class and Stream mapping, but am having no luck. It looked something like this:

            recordsList.stream()
                .filter(record -> record.getSortKey().contains(userId))
                .collect(Collectors.toList());
2 Answers

Firstly, you need to provide the alternative response object for the case when userId is null. For that, you need to use the same conditional logic (it's not a task for streams).

In the stream, you need to transform each Wrapper object the matches the predicate to your target type. Which can be done using map() operation.

private List<ResponseVo> populateResponse(String userId, String type) {
    
    if (userId == null) {
        return Collections.singletonList(buildResultsResponse(record));
    }
    
    return logRepo.getEntities(type, userId).stream()
        .filter(record -> record.getSortKey().contains(userId)) // Stream<Wrapper>
        .map(record -> buildResultsResponse(record))            // Stream<ResponseVo>
        .toList();                                              // for Java 16+ or collect(Collectors.toList())
}

It is possible with a single chain of calls starting with the Optional wrapper around the userId.

final List<ResponseVo> responseVoList = Optional
    .ofNullable(userId)                                // nullable userId
    .map(id -> recordsList.stream()                    // if non-null
            .filter(r -> r.getSortKey().contains(id))) // ... filter some out
    .orElseGet(recordsList::stream)                    // or else use all
    .map(this::buildResultsResponse)                   // build the response
    .collect(Collectors.toList());                     // pack as a List
Related