Skip to content

Commit

Permalink
replace .collect(Collectors.toList()) with toList (#2905)
Browse files Browse the repository at this point in the history
* replace .collect(Collectors.toList()) with toList

> Stream.toList() provides a List implementation that is immutable (type ImmutableCollections.ListN that cannot be added to or sorted) similar to that provided by List.of() and in contrast to the mutable (can be changed and sorted) ArrayList provided by Stream.collect(Collectors.toList()).

* Fix unused and star imports

* Fix type errors when moving to toList()

By reverting back to collect

* More unused imports

---------

Co-authored-by: Tim Yates <[email protected]>
  • Loading branch information
sdelamo and timyates authored Apr 25, 2024
1 parent ee8cf96 commit fcd0ea4
Show file tree
Hide file tree
Showing 46 changed files with 88 additions and 109 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -294,7 +294,7 @@ public <T, R> Flux<R> findAll(@NonNull PreparedQuery<T, R> pq) {
return result.byPage().flatMap(response -> {
CosmosUtils.processDiagnostics(cosmosDiagnosticsProcessor, CosmosDiagnosticsProcessor.QUERY_ITEMS, response.getCosmosDiagnostics(),
response.getActivityId(), response.getRequestCharge());
return Flux.fromIterable(response.getResults().stream().map(item -> cosmosSerde.deserialize(item, argument)).collect(Collectors.toList()));
return Flux.fromIterable(response.getResults().stream().map(item -> cosmosSerde.deserialize(item, argument)).toList());
}).onErrorMap(e -> CosmosUtils.cosmosAccessException(cosmosDiagnosticsProcessor, CosmosDiagnosticsProcessor.QUERY_ITEMS,
FAILED_TO_QUERY_ITEMS, e));
}
Expand All @@ -312,7 +312,7 @@ public <T, R> Flux<R> findAll(@NonNull PreparedQuery<T, R> pq) {
return conversionService.convertRequired(item, resultType);
}
return null;
}).collect(Collectors.toList()));
}).toList());
}).onErrorMap(e -> CosmosUtils.cosmosAccessException(cosmosDiagnosticsProcessor, CosmosDiagnosticsProcessor.QUERY_ITEMS,
FAILED_TO_QUERY_ITEMS, e));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,6 @@
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static java.time.format.DateTimeFormatter.ISO_OFFSET_DATE_TIME;
import static java.util.Arrays.asList;
Expand Down Expand Up @@ -176,7 +175,7 @@ public final class MongoQueryBuilder implements QueryBuilder {
String criterionPropertyName = getCriterionPropertyName(criterion.getProperty(), context);
if (value instanceof Iterable<?> iterable) {
List<?> values = CollectionUtils.iterableToList(iterable);
obj.put(criterionPropertyName, singletonMap("$in", values.stream().map(val -> valueRepresentation(context, propertyPath, val)).collect(Collectors.toList())));
obj.put(criterionPropertyName, singletonMap("$in", values.stream().map(val -> valueRepresentation(context, propertyPath, val)).toList()));
} else {
obj.put(criterionPropertyName, singletonMap("$in", singletonList(valueRepresentation(context, propertyPath, value))));
}
Expand All @@ -187,7 +186,7 @@ public final class MongoQueryBuilder implements QueryBuilder {
String criterionPropertyName = getCriterionPropertyName(criterion.getProperty(), context);
if (value instanceof Iterable<?> iterable) {
List<?> values = CollectionUtils.iterableToList(iterable);
obj.put(criterionPropertyName, singletonMap("$nin", values.stream().map(val -> valueRepresentation(context, propertyPath, val)).collect(Collectors.toList())));
obj.put(criterionPropertyName, singletonMap("$nin", values.stream().map(val -> valueRepresentation(context, propertyPath, val)).toList()));
} else {
obj.put(criterionPropertyName, singletonMap("$nin", singletonList(valueRepresentation(context, propertyPath, value))));
}
Expand Down Expand Up @@ -225,7 +224,7 @@ public final class MongoQueryBuilder implements QueryBuilder {
Object criteriaValue;
if (value instanceof Iterable<?> iterable) {
List<?> values = CollectionUtils.iterableToList(iterable);
criteriaValue = values.stream().map(val -> valueRepresentation(context, propertyPath, val)).collect(Collectors.toList());
criteriaValue = values.stream().map(val -> valueRepresentation(context, propertyPath, val)).toList();
} else {
criteriaValue = singletonList(valueRepresentation(context, propertyPath, value));
}
Expand Down Expand Up @@ -495,7 +494,7 @@ private void addLookups(Collection<JoinPath> joins, QueryState queryState) {
}
List<String> joined = joins.stream().map(JoinPath::getPath)
.sorted((o1, o2) -> Comparator.comparingInt(String::length).thenComparing(String::compareTo).compare(o1, o2))
.collect(Collectors.toList());
.toList();
for (String join : joined) {
StringJoiner rootPath = new StringJoiner(".");
StringJoiner currentEntityPath = new StringJoiner(".");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1214,7 +1214,7 @@ abstract class AbstractDocumentRepositorySpec extends Specification {
@Override
List<Author> call(TransactionStatus<Object> status) throws Exception {
try (Stream<Author> stream = authorRepository.queryByNameRegex(/.*e.*/)) {
return stream.collect(Collectors.toList())
return stream.toList()
}
}
})
Expand All @@ -1227,7 +1227,7 @@ abstract class AbstractDocumentRepositorySpec extends Specification {
@Override
List<Author> call(TransactionStatus<Object> status) throws Exception {
try (Stream<Author> stream = authorRepository.queryByNameRegex(/.*x.*/)) {
return stream.collect(Collectors.toList())
return stream.toList()
}
}
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -204,15 +204,15 @@ class JpaSpecificationCrudRepositorySpec extends Specification {
def people = [p1, p2, p3, p4, p5]
crudRepository.saveAll(people)
then:"can be ordered case insensitively"
def peopleIds = people.stream().map(p -> p.getId()).collect(Collectors.toList())
def peopleIds = people.stream().map(p -> p.getId()).toList()
Page<Person> personsPaged = crudRepository.findAll(new io.micronaut.data.jpa.repository.criteria.Specification<Person>() {
@Override
Predicate toPredicate(Root<Person> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
return root.get("id").in(peopleIds)
}
}, Pageable.from(0, 10, Sort.of(new Sort.Order("name", Sort.Order.Direction.ASC, true))))
personsPaged.totalSize == 5
def personNames = personsPaged.content.stream().map(p -> p.name).collect(Collectors.toList())
def personNames = personsPaged.content.stream().map(p -> p.name).toList()
personNames.size() == 5
personNames[0].toLowerCase() == "a"
personNames[1].toLowerCase() == "a"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -134,14 +134,14 @@ class ProjectionSpec extends Specification {
types.contains(Pet.PetType.CAT)

when:"a native query is used"
List names = petRepository.findPetNamesNative().collect(Collectors.toList())
List names = petRepository.findPetNamesNative().toList()

then:
names.size() == 3
names.containsAll(["A", "B", "C"])

when:"a native query is used"
types = petRepository.findPetTypesNative().collect(Collectors.toList())
types = petRepository.findPetTypesNative().toList()

then:
types.size() == 2
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,6 @@
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

Expand Down Expand Up @@ -689,7 +688,7 @@ public <T> Iterable<T> updateAll(@NonNull UpdateBatchOperation<T> operation) {
op.update();
return op.getEntity();
})
.collect(Collectors.toList());
.toList();
}
JdbcEntitiesOperations<T> op = new JdbcEntitiesOperations<>(ctx, persistentEntity, operation, storedQuery);
op.update();
Expand Down Expand Up @@ -751,7 +750,7 @@ public <T> Iterable<T> persistAll(@NonNull InsertBatchOperation<T> operation) {
op.persist();
return op.getEntity();
})
.collect(Collectors.toList());
.toList();
} else {
JdbcEntitiesOperations<T> op = new JdbcEntitiesOperations<>(ctx, persistentEntity, operation, storedQuery, true);
op.persist();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ class H2StreamingStatementSpec extends Specification {
personRepository.save(new Person(name: 'd'))

when:
def list = personRepository.findAllAndStream().collect(Collectors.toList())
def list = personRepository.findAllAndStream().toList()

then:
list.size() == 4
Expand Down
3 changes: 1 addition & 2 deletions data-model/src/main/java/io/micronaut/data/model/Page.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@
import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
* Inspired by the Spring Data's {@code Page} and GORM's {@code PagedResultList}, this models a type that supports
Expand Down Expand Up @@ -72,7 +71,7 @@ default int getTotalPages() {
*/
@Override
default @NonNull <T2> Page<T2> map(Function<T, T2> function) {
List<T2> content = getContent().stream().map(function).collect(Collectors.toList());
List<T2> content = getContent().stream().map(function).toList();
return new DefaultPage<>(content, getPageable(), getTotalSize());
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
*/
package io.micronaut.data.model;

import io.micronaut.core.annotation.NonNull;
import io.micronaut.core.annotation.Nullable;
import io.micronaut.core.beans.BeanIntrospection;
import io.micronaut.core.naming.NameUtils;
import io.micronaut.core.util.ArgumentUtils;
Expand All @@ -24,11 +26,13 @@
import io.micronaut.data.model.naming.NamingStrategy;
import io.micronaut.data.model.runtime.RuntimePersistentEntity;

import io.micronaut.core.annotation.NonNull;
import io.micronaut.core.annotation.Nullable;

import java.util.*;
import java.util.stream.Collectors;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;

import static io.micronaut.data.model.AssociationUtils.CAMEL_CASE_SPLIT_PATTERN;

Expand Down Expand Up @@ -139,7 +143,7 @@ default Collection<? extends Association> getAssociations() {
.stream()
.filter(bp -> bp instanceof Association)
.map(bp -> (Association) bp)
.collect(Collectors.toList());
.toList();
}

/**
Expand All @@ -152,7 +156,7 @@ default Collection<? extends Association> getAssociations() {
return getPersistentProperties().stream()
.filter(p -> p instanceof Embedded)
.map(p -> (Embedded) p)
.collect(Collectors.toList());
.toList();
}

/**
Expand Down Expand Up @@ -236,7 +240,7 @@ default String getSimpleName() {
default Optional<String> getPath(String camelCasePath) {
List<String> path = Arrays.stream(CAMEL_CASE_SPLIT_PATTERN.split(camelCasePath))
.map(NameUtils::decapitalize)
.collect(Collectors.toList());
.toList();

if (CollectionUtils.isNotEmpty(path)) {
Iterator<String> i = path.iterator();
Expand Down
3 changes: 1 addition & 2 deletions data-model/src/main/java/io/micronaut/data/model/Slice.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@
import java.util.Iterator;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
* Inspired by the Spring Data's {@code Slice} and GORM's {@code PagedResultList}, this models a type that supports
Expand Down Expand Up @@ -127,7 +126,7 @@ default Iterator<T> iterator() {
* @return A new slice with the mapped content
*/
default @NonNull <T2> Slice<T2> map(Function<T, T2> function) {
List<T2> content = getContent().stream().map(function).collect(Collectors.toList());
List<T2> content = getContent().stream().map(function).toList();
return new DefaultSlice<>(content, getPageable());
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
* The abstract implementation of {@link PersistentEntityCriteriaDelete}.
Expand Down Expand Up @@ -117,7 +116,7 @@ public PersistentEntityCriteriaDelete<T> where(Predicate... restrictions) {
Objects.requireNonNull(restrictions);
if (restrictions.length > 0) {
predicate = restrictions.length == 1 ? restrictions[0] : new ConjunctionPredicate(
Arrays.stream(restrictions).sequential().map(x -> (IExpression<Boolean>) x).collect(Collectors.toList())
Arrays.stream(restrictions).sequential().map(x -> (IExpression<Boolean>) x).toList()
);
} else {
predicate = null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,6 @@
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

import static io.micronaut.data.model.jpa.criteria.impl.CriteriaUtils.hasVersionPredicate;
import static io.micronaut.data.model.jpa.criteria.impl.CriteriaUtils.notSupportedOperation;
Expand Down Expand Up @@ -118,7 +117,7 @@ public QueryModel getQueryModel() {
return Sort.Order.asc(name);
}
return Sort.Order.desc(name);
}).collect(Collectors.toList());
}).toList();
qm.sort(Sort.of(sortOrders));
}
for (Map.Entry<String, Joiner.Joined> e : joiner.getJoins().entrySet()) {
Expand Down Expand Up @@ -214,7 +213,7 @@ public PersistentEntityCriteriaQuery<T> where(Predicate... restrictions) {
Objects.requireNonNull(restrictions);
if (restrictions.length > 0) {
predicate = restrictions.length == 1 ? restrictions[0] : new ConjunctionPredicate(
Arrays.stream(restrictions).sequential().map(x -> (IExpression<Boolean>) x).collect(Collectors.toList())
Arrays.stream(restrictions).sequential().map(x -> (IExpression<Boolean>) x).toList()
);
} else {
predicate = null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

import static io.micronaut.data.model.jpa.criteria.impl.CriteriaUtils.notSupportedOperation;
import static io.micronaut.data.model.jpa.criteria.impl.CriteriaUtils.requireParameter;
Expand Down Expand Up @@ -175,7 +174,7 @@ public PersistentEntityCriteriaUpdate<T> where(Predicate... restrictions) {
Objects.requireNonNull(restrictions);
if (restrictions.length > 0) {
predicate = restrictions.length == 1 ? restrictions[0] : new ConjunctionPredicate(
Arrays.stream(restrictions).sequential().map(x -> (IExpression<Boolean>) x).collect(Collectors.toList())
Arrays.stream(restrictions).sequential().map(x -> (IExpression<Boolean>) x).toList()
);
} else {
predicate = null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
* Criteria util class.
Expand Down Expand Up @@ -63,7 +62,7 @@ public static boolean isComparable(@NonNull Class<?> clazz) {
}

public static List<IExpression<Boolean>> requireBoolExpressions(Iterable<? extends Expression<?>> restrictions) {
return CollectionUtils.iterableToList(restrictions).stream().map(CriteriaUtils::requireBoolExpression).collect(Collectors.toList());
return CollectionUtils.iterableToList(restrictions).stream().map(CriteriaUtils::requireBoolExpression).toList();
}

public static IExpression<Boolean> requireBoolExpression(Expression<?> exp) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@
import java.util.Iterator;
import java.util.List;
import java.util.StringJoiner;
import java.util.stream.Collectors;

/**
* The predicate visitor to convert criteria predicates to {@link QueryModel}.
Expand Down Expand Up @@ -323,12 +322,12 @@ public void visit(PersistentPropertyInValuesPredicate<?> inValues) {
state.negated = false;
add(Restrictions.notIn(
getPropertyPath(inValues),
values.stream().map(this::asValue).collect(Collectors.toList())
values.stream().map(this::asValue).toList()
));
} else {
add(Restrictions.in(
getPropertyPath(inValues),
values.stream().map(this::asValue).collect(Collectors.toList())
values.stream().map(this::asValue).toList()
));
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -377,7 +377,7 @@ private <T extends QueryModel.PropertyCriterion> CriterionHandler<T> likeConcatC
}
}
return (Runnable) () -> query.append(p);
}).collect(Collectors.toList()));
}).toList());
};
}

Expand Down
Loading

0 comments on commit fcd0ea4

Please sign in to comment.