Is there any way to Stream Map Filter & Map back to original object in Java 8?

AshwinK :

Is there any way to Stream the list --> map --> filter --> map back to original object type of list?

There is solution if we are doing it using foreach as below:

List<Query> updatedQueries = getUpdatedQueries();

List<Query> finalQueries = new ArrayList<>();
updatedQueries.forEach(query -> {

    Period period = getPeriodRequest(query);
    boolean isValidPeriod = periodService.validatePeriodicity(period);
    if(isValidPeriod &&  isMandatory(period)){
        finalQueries.add(query);
    }

});

But is there any way to do it using following way ?

List<Query> updatedQueries = getUpdatedQueries();

List<Query> finalQueries = updatedQueries
        .stream()
        .map(this::getPeriodRequest) //returns the object of type Period
        .filter(period->periodService.validatePeriodicity(period))
        .filter(this::isMandatory)
        //is any way we can map back to Query object (without any object translation  function)
        .collect(Collectors.toList());
Hadi J :

Try this one

List<Query> finalQueries = updatedQueries
    .stream().filter(query->{
        Period period = getPeriodRequest(query);
        return periodService.validatePeriodicity(period )&& isMandatory(period))
    })
    .collect(Collectors.toList());

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=71998&siteId=1