Skip to content

Commit

Permalink
replace .collect(toUnmodifiableList()) with .toList() (#84760)
Browse files Browse the repository at this point in the history
Replace collect with a simipler toList call that also creates immutable
collection.
  • Loading branch information
idegtiarenko committed Mar 10, 2022
1 parent 83d0e8e commit 01c5bc0
Show file tree
Hide file tree
Showing 63 changed files with 90 additions and 194 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ private static List<String> flagsFinal(final List<String> userDefinedJvmOptions)
Stream.of("-Xshare:off"),
Stream.of("-XX:+PrintFlagsFinal"),
Stream.of("-version")
).reduce(Stream::concat).get().collect(Collectors.toUnmodifiableList());
).reduce(Stream::concat).get().toList();
final Process process = new ProcessBuilder().command(command).start();
final List<String> output = readLinesFromInputStream(process.getInputStream());
final List<String> error = readLinesFromInputStream(process.getErrorStream());
Expand All @@ -119,7 +119,7 @@ private static List<String> flagsFinal(final List<String> userDefinedJvmOptions)

private static List<String> readLinesFromInputStream(final InputStream is) throws IOException {
try (InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8); BufferedReader br = new BufferedReader(isr)) {
return br.lines().collect(Collectors.toUnmodifiableList());
return br.lines().toList();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -125,9 +125,7 @@ private List<String> jvmOptions(final Path config, Path plugins, final String es
final List<String> jvmOptions = readJvmOptionsFiles(config);

if (esJavaOpts != null) {
jvmOptions.addAll(
Arrays.stream(esJavaOpts.split("\\s+")).filter(Predicate.not(String::isBlank)).collect(Collectors.toUnmodifiableList())
);
jvmOptions.addAll(Arrays.stream(esJavaOpts.split("\\s+")).filter(Predicate.not(String::isBlank)).toList());
}

final List<String> substitutedJvmOptions = substitutePlaceholders(jvmOptions, Collections.unmodifiableMap(substitutions));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,10 +63,7 @@ public X509ExtendedTrustManager createTrustManager() {

@Override
public Collection<? extends StoredCertificate> getConfiguredCertificates() {
return configs.stream()
.map(SslTrustConfig::getConfiguredCertificates)
.flatMap(Collection::stream)
.collect(Collectors.toUnmodifiableList());
return configs.stream().map(SslTrustConfig::getConfiguredCertificates).flatMap(Collection::stream).toList();
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@
import java.util.Locale;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import javax.net.ssl.KeyManager;
Expand Down Expand Up @@ -281,10 +280,7 @@ public List<? extends X509Certificate> getX509CertificateChain() {
if (certificates == null || certificates.length == 0) {
return List.of();
}
return Stream.of(certificates)
.filter(c -> c instanceof X509Certificate)
.map(X509Certificate.class::cast)
.collect(Collectors.toUnmodifiableList());
return Stream.of(certificates).filter(c -> c instanceof X509Certificate).map(X509Certificate.class::cast).toList();
} catch (KeyStoreException e) {
throw exceptionHandler.apply(e);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509ExtendedTrustManager;
Expand Down Expand Up @@ -87,7 +86,7 @@ public X509ExtendedTrustManager createTrustManager() {
}

private List<Path> resolveFiles() {
return this.certificateAuthorities.stream().map(this::resolveFile).collect(Collectors.toUnmodifiableList());
return this.certificateAuthorities.stream().map(this::resolveFile).toList();
}

private Path resolveFile(String other) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.TrustManagerFactory;
Expand Down Expand Up @@ -121,7 +120,7 @@ public List<Tuple<PrivateKey, X509Certificate>> getKeys(boolean filterKeystore)
return null;
})
.filter(Objects::nonNull)
.collect(Collectors.toUnmodifiableList());
.toList();
}

@Override
Expand All @@ -136,7 +135,7 @@ public Collection<StoredCertificate> getConfiguredCertificates() {
firstElement = false;
}
return certificates.stream();
}).collect(Collectors.toUnmodifiableList());
}).toList();
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
import java.util.Enumeration;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import javax.net.ssl.X509ExtendedTrustManager;

Expand Down Expand Up @@ -73,7 +72,7 @@ public Collection<? extends StoredCertificate> getConfiguredCertificates() {
} else {
return null;
}
}).filter(Objects::nonNull).collect(Collectors.toUnmodifiableList());
}).filter(Objects::nonNull).toList();
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,13 @@
import org.elasticsearch.indices.SystemIndexDescriptor;
import org.elasticsearch.test.ESTestCase;

import java.util.stream.Collectors;

import static org.hamcrest.Matchers.contains;

public class KibanaPluginTests extends ESTestCase {

public void testKibanaIndexNames() {
assertThat(
new KibanaPlugin().getSystemIndexDescriptors(Settings.EMPTY)
.stream()
.map(SystemIndexDescriptor::getIndexPattern)
.collect(Collectors.toUnmodifiableList()),
new KibanaPlugin().getSystemIndexDescriptors(Settings.EMPTY).stream().map(SystemIndexDescriptor::getIndexPattern).toList(),
contains(".kibana_*", ".reporting-*", ".apm-agent-configuration*", ".apm-custom-link*")
);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

/**
Expand Down Expand Up @@ -171,12 +170,10 @@ static List<SearchShard> buildSearchShards(List<? extends SearchPhaseResult> res
.filter(Objects::nonNull)
.map(SearchPhaseResult::getSearchShardTarget)
.map(e -> new SearchShard(e.getClusterAlias(), e.getShardId()))
.collect(Collectors.toUnmodifiableList());
.toList();
}

static List<SearchShard> buildSearchShards(GroupShardsIterator<SearchShardIterator> its) {
return StreamSupport.stream(its.spliterator(), false)
.map(e -> new SearchShard(e.getClusterAlias(), e.shardId()))
.collect(Collectors.toUnmodifiableList());
return StreamSupport.stream(its.spliterator(), false).map(e -> new SearchShard(e.getClusterAlias(), e.shardId())).toList();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,7 @@ static class UnknownRole extends DiscoveryNodeRole {
static {
final List<Field> roleFields = Arrays.stream(DiscoveryNodeRole.class.getFields())
.filter(f -> f.getType().equals(DiscoveryNodeRole.class))
.collect(Collectors.toUnmodifiableList());
.toList();
// this will detect duplicate role names
final Map<String, DiscoveryNodeRole> roleMap = roleFields.stream().map(f -> {
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -562,10 +562,7 @@ public static String getPeerRecoveryRetentionLeaseId(ShardRouting shardRouting)
* Returns a list of peer recovery retention leases installed in this replication group
*/
public List<RetentionLease> getPeerRecoveryRetentionLeases() {
return getRetentionLeases().leases()
.stream()
.filter(lease -> PEER_RECOVERY_RETENTION_LEASE_SOURCE.equals(lease.source()))
.collect(Collectors.toUnmodifiableList());
return getRetentionLeases().leases().stream().filter(lease -> PEER_RECOVERY_RETENTION_LEASE_SOURCE.equals(lease.source())).toList();
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
* An "associated index" is an index that is related to or derived from a system
Expand Down Expand Up @@ -106,7 +105,7 @@ static Automaton buildAutomaton(String pattern) {
*/
@Override
public List<String> getMatchingIndices(Metadata metadata) {
return metadata.indices().keySet().stream().filter(this::matchesIndexPattern).collect(Collectors.toUnmodifiableList());
return metadata.indices().keySet().stream().filter(this::matchesIndexPattern).toList();
}

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

import static org.elasticsearch.indices.AssociatedIndexDescriptor.buildAutomaton;

Expand Down Expand Up @@ -91,7 +90,7 @@ public String getDataStreamName() {
* @return List of names of backing indices
*/
public List<String> getBackingIndexNames(Metadata metadata) {
return metadata.indices().keySet().stream().filter(this.characterRunAutomaton::run).collect(Collectors.toUnmodifiableList());
return metadata.indices().keySet().stream().filter(this.characterRunAutomaton::run).toList();
}

public String getDescription() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
* A system index descriptor describes one or more system indices. It can match a number of indices using
Expand Down Expand Up @@ -400,7 +399,7 @@ public boolean matchesIndexPattern(String index) {
*/
@Override
public List<String> getMatchingIndices(Metadata metadata) {
return metadata.indices().keySet().stream().filter(this::matchesIndexPattern).collect(Collectors.toUnmodifiableList());
return metadata.indices().keySet().stream().filter(this::matchesIndexPattern).toList();
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static java.util.stream.Collectors.toUnmodifiableList;
import static org.elasticsearch.tasks.TaskResultsService.TASKS_DESCRIPTOR;
import static org.elasticsearch.tasks.TaskResultsService.TASKS_FEATURE_NAME;

Expand Down Expand Up @@ -513,15 +512,15 @@ static void checkForOverlappingPatterns(Map<String, Feature> sourceToFeature) {
.stream()
.flatMap(entry -> entry.getValue().getIndexDescriptors().stream().map(descriptor -> new Tuple<>(entry.getKey(), descriptor)))
.sorted(Comparator.comparing(d -> d.v1() + ":" + d.v2().getIndexPattern())) // Consistent ordering -> consistent error message
.collect(Collectors.toUnmodifiableList());
.toList();
List<Tuple<String, SystemDataStreamDescriptor>> sourceDataStreamDescriptorPair = sourceToFeature.entrySet()
.stream()
.filter(entry -> entry.getValue().getDataStreamDescriptors().isEmpty() == false)
.flatMap(
entry -> entry.getValue().getDataStreamDescriptors().stream().map(descriptor -> new Tuple<>(entry.getKey(), descriptor))
)
.sorted(Comparator.comparing(d -> d.v1() + ":" + d.v2().getDataStreamName())) // Consistent ordering -> consistent error message
.collect(Collectors.toUnmodifiableList());
.toList();

// This is O(n^2) with the number of system index descriptors, and each check is quadratic with the number of states in the
// automaton, but the absolute number of system index descriptors should be quite small (~10s at most), and the number of states
Expand All @@ -533,7 +532,7 @@ static void checkForOverlappingPatterns(Map<String, Feature> sourceToFeature) {
d -> overlaps(descriptorToCheck.v2(), d.v2())
|| (d.v2().getAliasName() != null && descriptorToCheck.v2().matchesIndexPattern(d.v2().getAliasName()))
)
.collect(toUnmodifiableList());
.toList();
if (descriptorsMatchingThisPattern.isEmpty() == false) {
throw new IllegalStateException(
"a system index descriptor ["
Expand All @@ -552,7 +551,7 @@ static void checkForOverlappingPatterns(Map<String, Feature> sourceToFeature) {
dsTuple -> descriptorToCheck.v2().matchesIndexPattern(dsTuple.v2().getDataStreamName())
|| overlaps(descriptorToCheck.v2().getIndexPattern(), dsTuple.v2().getBackingIndexPattern())
)
.collect(toUnmodifiableList());
.toList();
if (dataStreamsMatching.isEmpty() == false) {
throw new IllegalStateException(
"a system index descriptor ["
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -404,7 +404,7 @@ public List<CancellableTask> setBan(TaskId parentTaskId, String reason, Transpor
ban.registerChannel(DIRECT_CHANNEL_TRACKER);
}
}
return cancellableTasks.getByParent(parentTaskId).map(t -> t.task).collect(Collectors.toUnmodifiableList());
return cancellableTasks.getByParent(parentTaskId).map(t -> t.task).toList();
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,6 @@
import java.util.Objects;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static java.util.stream.Collectors.toList;
Expand Down Expand Up @@ -445,7 +444,7 @@ private List<String> resolveMetrics(List<TimeSeriesMetricSelector> selectors) {
for (TimeSeriesMetricSelector selector : selectors) {
metrics = metrics.filter(selector.asPredicate());
}
return metrics.collect(Collectors.toUnmodifiableList());
return metrics.toList();
}

private SearchRequest searchInRange(List<String> metrics, List<TimeSeriesDimensionSelector> dimensions, long from, long to, int size) {
Expand Down
13 changes: 3 additions & 10 deletions server/src/test/java/org/elasticsearch/common/util/MapsTests.java
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,7 @@ public void testConcatenateEntryToImmutableMap() {
final String key = randomValueOtherThanMany(keys::contains, () -> randomAlphaOfLength(16));
final String value = randomAlphaOfLength(16);
final Map<String, String> concatenation = Maps.copyMapWithAddedEntry(map, key, value);
assertMapEntriesAndImmutability(
concatenation,
Stream.concat(entries.stream(), Stream.of(entry(key, value))).collect(Collectors.toUnmodifiableList())
);
assertMapEntriesAndImmutability(concatenation, Stream.concat(entries.stream(), Stream.of(entry(key, value))).toList());
}

public void testAddEntryInImmutableMap() {
Expand All @@ -67,10 +64,7 @@ public void testAddEntryInImmutableMap() {
final String key = randomValueOtherThanMany(keys::contains, () -> randomAlphaOfLength(16));
final String value = randomAlphaOfLength(16);
final Map<String, String> add = Maps.copyMapWithAddedOrReplacedEntry(map, key, value);
assertMapEntriesAndImmutability(
add,
Stream.concat(entries.stream(), Stream.of(entry(key, value))).collect(Collectors.toUnmodifiableList())
);
assertMapEntriesAndImmutability(add, Stream.concat(entries.stream(), Stream.of(entry(key, value))).toList());
}

public void testReplaceEntryInImmutableMap() {
Expand All @@ -88,8 +82,7 @@ public void testReplaceEntryInImmutableMap() {
final Map<String, String> replaced = Maps.copyMapWithAddedOrReplacedEntry(map, key, value);
assertMapEntriesAndImmutability(
replaced,
Stream.concat(entries.stream().filter(e -> key.equals(e.getKey()) == false), Stream.of(entry(key, value)))
.collect(Collectors.toUnmodifiableList())
Stream.concat(entries.stream().filter(e -> key.equals(e.getKey()) == false), Stream.of(entry(key, value))).toList()
);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static org.hamcrest.Matchers.is;
Expand Down Expand Up @@ -84,7 +83,7 @@ public void testIndexOf() {
final List<String> list = Stream.generate(() -> randomAlphaOfLengthBetween(3, 9))
.limit(randomIntBetween(10, 30))
.distinct()
.collect(Collectors.toUnmodifiableList());
.toList();
for (int i = 0; i < list.size(); i++) {
final String val = list.get(i);
assertThat(Iterables.indexOf(list, val::equals), is(i));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -284,13 +284,9 @@ public void append(LogEvent event) {
.filter(unsupportedTZIdsPredicate.negate())
.filter(unsupportedZoneIdsPredicate.negate())
.sorted()
.collect(Collectors.toUnmodifiableList());
.toList();

JAVA_ZONE_IDS = ZoneId.getAvailableZoneIds()
.stream()
.filter(unsupportedZoneIdsPredicate.negate())
.sorted()
.collect(Collectors.toUnmodifiableList());
JAVA_ZONE_IDS = ZoneId.getAvailableZoneIds().stream().filter(unsupportedZoneIdsPredicate.negate()).sorted().toList();
}

@SuppressForbidden(reason = "force log4j and netty sysprops")
Expand Down

0 comments on commit 01c5bc0

Please sign in to comment.