瀏覽代碼

Replace needless map builder with Map.of(..) (#91310)

Ievgen Degtiarenko 2 年之前
父節點
當前提交
cd820b6f6d

+ 5 - 5
modules/repository-gcs/src/main/java/org/elasticsearch/repositories/gcs/GoogleCloudStorageBlobStore.java

@@ -28,7 +28,6 @@ import org.elasticsearch.common.blobstore.BlobStore;
 import org.elasticsearch.common.blobstore.DeleteResult;
 import org.elasticsearch.common.blobstore.support.BlobMetadata;
 import org.elasticsearch.common.bytes.BytesReference;
-import org.elasticsearch.common.collect.MapBuilder;
 import org.elasticsearch.common.hash.MessageDigests;
 import org.elasticsearch.common.io.Streams;
 import org.elasticsearch.common.io.stream.ReleasableBytesStreamOutput;
@@ -50,6 +49,7 @@ import java.nio.file.FileAlreadyExistsException;
 import java.util.ArrayList;
 import java.util.Base64;
 import java.util.Collections;
+import java.util.HashMap;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
@@ -151,7 +151,7 @@ class GoogleCloudStorageBlobStore implements BlobStore {
      */
     Map<String, BlobMetadata> listBlobsByPrefix(String path, String prefix) throws IOException {
         final String pathPrefix = buildKey(path, prefix);
-        final MapBuilder<String, BlobMetadata> mapBuilder = MapBuilder.newMapBuilder();
+        final Map<String, BlobMetadata> mapBuilder = new HashMap<>();
         SocketAccess.doPrivilegedVoidIOException(
             () -> client().list(bucketName, BlobListOption.currentDirectory(), BlobListOption.prefix(pathPrefix))
                 .iterateAll()
@@ -163,12 +163,12 @@ class GoogleCloudStorageBlobStore implements BlobStore {
                     }
                 })
         );
-        return mapBuilder.immutableMap();
+        return Map.copyOf(mapBuilder);
     }
 
     Map<String, BlobContainer> listChildren(BlobPath path) throws IOException {
         final String pathStr = path.buildAsString();
-        final MapBuilder<String, BlobContainer> mapBuilder = MapBuilder.newMapBuilder();
+        final Map<String, BlobContainer> mapBuilder = new HashMap<>();
         SocketAccess.doPrivilegedVoidIOException(
             () -> client().list(bucketName, BlobListOption.currentDirectory(), BlobListOption.prefix(pathStr))
                 .iterateAll()
@@ -184,7 +184,7 @@ class GoogleCloudStorageBlobStore implements BlobStore {
                     }
                 })
         );
-        return mapBuilder.immutableMap();
+        return Map.copyOf(mapBuilder);
     }
 
     /**

+ 3 - 6
modules/repository-gcs/src/main/java/org/elasticsearch/repositories/gcs/GoogleCloudStorageService.java

@@ -23,7 +23,6 @@ import com.google.cloud.storage.StorageOptions;
 import org.apache.logging.log4j.LogManager;
 import org.apache.logging.log4j.Logger;
 import org.elasticsearch.common.Strings;
-import org.elasticsearch.common.collect.MapBuilder;
 import org.elasticsearch.common.util.Maps;
 import org.elasticsearch.core.SuppressForbidden;
 import org.elasticsearch.core.TimeValue;
@@ -179,11 +178,9 @@ public class GoogleCloudStorageService {
         final StorageOptions.Builder storageOptionsBuilder = StorageOptions.newBuilder()
             .setTransportOptions(httpTransportOptions)
             .setHeaderProvider(() -> {
-                final MapBuilder<String, String> mapBuilder = MapBuilder.newMapBuilder();
-                if (Strings.hasLength(gcsClientSettings.getApplicationName())) {
-                    mapBuilder.put("user-agent", gcsClientSettings.getApplicationName());
-                }
-                return mapBuilder.immutableMap();
+                return Strings.hasLength(gcsClientSettings.getApplicationName())
+                    ? Map.of("user-agent", gcsClientSettings.getApplicationName())
+                    : Map.of();
             });
         if (Strings.hasLength(gcsClientSettings.getHost())) {
             storageOptionsBuilder.setHost(gcsClientSettings.getHost());

+ 14 - 15
plugins/discovery-gce/qa/gce/src/yamlRestTest/java/org/elasticsearch/cloud/gce/GCEFixture.java

@@ -9,7 +9,6 @@ package org.elasticsearch.cloud.gce;
 
 import org.apache.http.client.methods.HttpGet;
 import org.elasticsearch.common.Strings;
-import org.elasticsearch.common.collect.MapBuilder;
 import org.elasticsearch.common.path.PathTrie;
 import org.elasticsearch.core.SuppressForbidden;
 import org.elasticsearch.rest.RestStatus;
@@ -192,22 +191,22 @@ public class GCEFixture extends AbstractHttpFixture {
             jsonBuilder().startObject()
                 .field(
                     "error",
-                    MapBuilder.<String, Object>newMapBuilder()
-                        .put(
+                    Map.<String, Object>ofEntries(
+                        Map.entry(
                             "errors",
-                            Collections.singletonList(
-                                MapBuilder.<String, Object>newMapBuilder()
-                                    .put("domain", "global")
-                                    .put("reason", "required")
-                                    .put("message", message)
-                                    .put("locationType", "header")
-                                    .put("location", code)
-                                    .immutableMap()
+                            List.of(
+                                Map.<String, Object>ofEntries(
+                                    Map.entry("domain", "global"),
+                                    Map.entry("reason", "required"),
+                                    Map.entry("message", message),
+                                    Map.entry("locationType", "header"),
+                                    Map.entry("location", code)
+                                )
                             )
-                        )
-                        .put("code", status.getStatus())
-                        .put("message", message)
-                        .immutableMap()
+                        ),
+                        Map.entry("code", status.getStatus()),
+                        Map.entry("message", message)
+                    )
                 )
                 .endObject()
         );

+ 5 - 4
server/src/internalClusterTest/java/org/elasticsearch/recovery/FullRollingRestartIT.java

@@ -16,7 +16,6 @@ import org.elasticsearch.cluster.metadata.IndexMetadata;
 import org.elasticsearch.cluster.routing.RecoverySource;
 import org.elasticsearch.cluster.routing.UnassignedInfo;
 import org.elasticsearch.common.Priority;
-import org.elasticsearch.common.collect.MapBuilder;
 import org.elasticsearch.common.settings.Settings;
 import org.elasticsearch.core.TimeValue;
 import org.elasticsearch.indices.recovery.RecoveryState;
@@ -24,6 +23,8 @@ import org.elasticsearch.test.ESIntegTestCase;
 import org.elasticsearch.test.ESIntegTestCase.ClusterScope;
 import org.elasticsearch.test.ESIntegTestCase.Scope;
 
+import java.util.Map;
+
 import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;
 import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount;
 
@@ -51,7 +52,7 @@ public class FullRollingRestartIT extends ESIntegTestCase {
         for (int i = 0; i < 1000; i++) {
             client().prepareIndex("test")
                 .setId(Long.toString(i))
-                .setSource(MapBuilder.<String, Object>newMapBuilder().put("test", "value" + i).map())
+                .setSource(Map.<String, Object>of("test", "value" + i))
                 .execute()
                 .actionGet();
         }
@@ -59,7 +60,7 @@ public class FullRollingRestartIT extends ESIntegTestCase {
         for (int i = 1000; i < 2000; i++) {
             client().prepareIndex("test")
                 .setId(Long.toString(i))
-                .setSource(MapBuilder.<String, Object>newMapBuilder().put("test", "value" + i).map())
+                .setSource(Map.<String, Object>of("test", "value" + i))
                 .execute()
                 .actionGet();
         }
@@ -190,7 +191,7 @@ public class FullRollingRestartIT extends ESIntegTestCase {
         for (int i = 0; i < 100; i++) {
             client().prepareIndex("test")
                 .setId(Long.toString(i))
-                .setSource(MapBuilder.<String, Object>newMapBuilder().put("test", "value" + i).map())
+                .setSource(Map.<String, Object>of("test", "value" + i))
                 .execute()
                 .actionGet();
         }

+ 4 - 3
server/src/internalClusterTest/java/org/elasticsearch/search/fields/SearchFieldsIT.java

@@ -14,7 +14,6 @@ import org.elasticsearch.action.search.SearchResponse;
 import org.elasticsearch.common.Strings;
 import org.elasticsearch.common.bytes.BytesArray;
 import org.elasticsearch.common.bytes.BytesReference;
-import org.elasticsearch.common.collect.MapBuilder;
 import org.elasticsearch.common.document.DocumentField;
 import org.elasticsearch.common.settings.Settings;
 import org.elasticsearch.common.time.DateFormatter;
@@ -337,11 +336,13 @@ public class SearchFieldsIT extends ESIntegTestCase {
         assertThat(response.getHits().getAt(2).getFields().get("date1").getValues().get(0), equalTo(120000L));
 
         logger.info("running doc['num1'].value * factor");
-        Map<String, Object> params = MapBuilder.<String, Object>newMapBuilder().put("factor", 2.0).map();
         response = client().prepareSearch()
             .setQuery(matchAllQuery())
             .addSort("num1", SortOrder.ASC)
-            .addScriptField("sNum1", new Script(ScriptType.INLINE, CustomScriptPlugin.NAME, "doc['num1'].value * factor", params))
+            .addScriptField(
+                "sNum1",
+                new Script(ScriptType.INLINE, CustomScriptPlugin.NAME, "doc['num1'].value * factor", Map.of("factor", 2.0))
+            )
             .get();
 
         assertThat(response.getHits().getTotalHits().value, equalTo(3L));

+ 4 - 6
server/src/main/java/org/elasticsearch/cluster/metadata/IndexMetadata.java

@@ -24,7 +24,6 @@ import org.elasticsearch.cluster.routing.allocation.decider.DiskThresholdDecider
 import org.elasticsearch.cluster.routing.allocation.decider.ShardsLimitAllocationDecider;
 import org.elasticsearch.common.Strings;
 import org.elasticsearch.common.collect.ImmutableOpenMap;
-import org.elasticsearch.common.collect.MapBuilder;
 import org.elasticsearch.common.compress.CompressedXContent;
 import org.elasticsearch.common.io.stream.StreamInput;
 import org.elasticsearch.common.io.stream.StreamOutput;
@@ -2421,7 +2420,7 @@ public class IndexMetadata implements Diffable<IndexMetadata>, ToXContentFragmen
                         }
                         builder.settings(settings);
                     } else if ("mappings".equals(currentFieldName)) {
-                        MapBuilder<String, Object> mappingSourceBuilder = MapBuilder.<String, Object>newMapBuilder();
+                        Map<String, Object> mappingSourceBuilder = new HashMap<>();
                         while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
                             if (token == XContentParser.Token.FIELD_NAME) {
                                 currentFieldName = parser.currentName();
@@ -2432,8 +2431,7 @@ public class IndexMetadata implements Diffable<IndexMetadata>, ToXContentFragmen
                                 throw new IllegalArgumentException("Unexpected token: " + token);
                             }
                         }
-                        Map<String, Object> mapping = mappingSourceBuilder.map();
-                        handleLegacyMapping(builder, mapping);
+                        handleLegacyMapping(builder, mappingSourceBuilder);
                     } else if ("in_sync_allocations".equals(currentFieldName)) {
                         while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
                             if (token == XContentParser.Token.FIELD_NAME) {
@@ -2457,7 +2455,7 @@ public class IndexMetadata implements Diffable<IndexMetadata>, ToXContentFragmen
                     }
                 } else if (token == XContentParser.Token.START_ARRAY) {
                     if ("mappings".equals(currentFieldName)) {
-                        MapBuilder<String, Object> mappingSourceBuilder = MapBuilder.<String, Object>newMapBuilder();
+                        Map<String, Object> mappingSourceBuilder = new HashMap<>();
                         while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
                             Map<String, Object> mapping;
                             if (token == XContentParser.Token.VALUE_EMBEDDED_OBJECT) {
@@ -2468,7 +2466,7 @@ public class IndexMetadata implements Diffable<IndexMetadata>, ToXContentFragmen
                             }
                             mappingSourceBuilder.putAll(mapping);
                         }
-                        handleLegacyMapping(builder, mappingSourceBuilder.map());
+                        handleLegacyMapping(builder, mappingSourceBuilder);
                     } else {
                         parser.skipChildren();
                     }

+ 4 - 6
server/src/main/java/org/elasticsearch/cluster/metadata/IndexTemplateMetadata.java

@@ -11,7 +11,6 @@ import org.elasticsearch.ElasticsearchParseException;
 import org.elasticsearch.cluster.Diff;
 import org.elasticsearch.cluster.SimpleDiffable;
 import org.elasticsearch.common.Strings;
-import org.elasticsearch.common.collect.MapBuilder;
 import org.elasticsearch.common.compress.CompressedXContent;
 import org.elasticsearch.common.io.stream.StreamInput;
 import org.elasticsearch.common.io.stream.StreamOutput;
@@ -440,11 +439,10 @@ public class IndexTemplateMetadata implements SimpleDiffable<IndexTemplateMetada
                             if (token == XContentParser.Token.FIELD_NAME) {
                                 currentFieldName = parser.currentName();
                             } else if (token == XContentParser.Token.START_OBJECT) {
-                                String mappingType = currentFieldName;
-                                Map<String, Object> mappingSource = MapBuilder.<String, Object>newMapBuilder()
-                                    .put(mappingType, parser.mapOrdered())
-                                    .map();
-                                builder.putMapping(mappingType, Strings.toString(XContentFactory.jsonBuilder().map(mappingSource)));
+                                builder.putMapping(
+                                    currentFieldName,
+                                    Strings.toString(XContentFactory.jsonBuilder().map(Map.of(currentFieldName, parser.mapOrdered())))
+                                );
                             }
                         }
                     } else if ("aliases".equals(currentFieldName)) {

+ 4 - 9
server/src/test/java/org/elasticsearch/action/admin/indices/template/put/PutIndexTemplateRequestTests.java

@@ -9,7 +9,6 @@ package org.elasticsearch.action.admin.indices.template.put;
 
 import org.elasticsearch.action.ActionRequestValidationException;
 import org.elasticsearch.action.admin.indices.alias.Alias;
-import org.elasticsearch.common.collect.MapBuilder;
 import org.elasticsearch.common.settings.Settings;
 import org.elasticsearch.test.ESTestCase;
 import org.elasticsearch.xcontent.XContentBuilder;
@@ -97,14 +96,10 @@ public class PutIndexTemplateRequestTests extends ESTestCase {
         {
             request1 = new PutIndexTemplateRequest("foo");
             request2 = new PutIndexTemplateRequest("bar");
-            Map<String, Object> nakedMapping = MapBuilder.<String, Object>newMapBuilder()
-                .put(
-                    "properties",
-                    MapBuilder.<String, Object>newMapBuilder()
-                        .put("bar", MapBuilder.<String, Object>newMapBuilder().put("type", "scaled_float").put("scaling_factor", 100).map())
-                        .map()
-                )
-                .map();
+            Map<String, Object> nakedMapping = Map.<String, Object>of(
+                "properties",
+                Map.<String, Object>of("bar", Map.<String, Object>of("type", "scaled_float", "scaling_factor", 100))
+            );
             request1.mapping(nakedMapping);
             request2.mapping(Map.of("_doc", nakedMapping));
             assertEquals(request1.mappings(), request2.mappings());

+ 7 - 8
server/src/test/java/org/elasticsearch/ingest/IngestStatsTests.java

@@ -8,17 +8,14 @@
 
 package org.elasticsearch.ingest;
 
-import org.elasticsearch.common.collect.MapBuilder;
 import org.elasticsearch.common.io.stream.BytesStreamOutput;
 import org.elasticsearch.common.io.stream.StreamInput;
 import org.elasticsearch.test.ESTestCase;
 
 import java.io.IOException;
-import java.util.Collections;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
-import java.util.stream.Stream;
 
 public class IngestStatsTests extends ESTestCase {
 
@@ -35,7 +32,7 @@ public class IngestStatsTests extends ESTestCase {
         IngestStats.PipelineStat pipeline1Stats = new IngestStats.PipelineStat("pipeline1", new IngestStats.Stats(3, 3, 3, 3));
         IngestStats.PipelineStat pipeline2Stats = new IngestStats.PipelineStat("pipeline2", new IngestStats.Stats(47, 97, 197, 297));
         IngestStats.PipelineStat pipeline3Stats = new IngestStats.PipelineStat("pipeline3", new IngestStats.Stats(0, 0, 0, 0));
-        return Stream.of(pipeline1Stats, pipeline2Stats, pipeline3Stats).toList();
+        return List.of(pipeline1Stats, pipeline2Stats, pipeline3Stats);
     }
 
     private Map<String, List<IngestStats.ProcessorStat>> createProcessorStats(List<IngestStats.PipelineStat> pipelineStats) {
@@ -48,10 +45,12 @@ public class IngestStatsTests extends ESTestCase {
             new IngestStats.Stats(47, 97, 197, 297)
         );
         // pipeline1 -> processor1,processor2; pipeline2 -> processor3
-        return MapBuilder.<String, List<IngestStats.ProcessorStat>>newMapBuilder()
-            .put(pipelineStats.get(0).getPipelineId(), Stream.of(processor1Stat, processor2Stat).toList())
-            .put(pipelineStats.get(1).getPipelineId(), Collections.singletonList(processor3Stat))
-            .map();
+        return Map.of(
+            pipelineStats.get(0).getPipelineId(),
+            List.of(processor1Stat, processor2Stat),
+            pipelineStats.get(1).getPipelineId(),
+            List.of(processor3Stat)
+        );
     }
 
     private IngestStats serialize(IngestStats stats) throws IOException {

+ 7 - 6
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ClientHelperTests.java

@@ -19,7 +19,6 @@ import org.elasticsearch.action.support.PlainActionFuture;
 import org.elasticsearch.client.internal.Client;
 import org.elasticsearch.cluster.ClusterState;
 import org.elasticsearch.cluster.node.DiscoveryNodes;
-import org.elasticsearch.common.collect.MapBuilder;
 import org.elasticsearch.common.settings.Settings;
 import org.elasticsearch.common.util.Maps;
 import org.elasticsearch.common.util.concurrent.ThreadContext;
@@ -283,10 +282,12 @@ public class ClientHelperTests extends ESTestCase {
             )
         );
         when(client.search(any())).thenReturn(searchFuture);
-        Map<String, String> headers = MapBuilder.<String, String>newMapBuilder()
-            .put(AuthenticationField.AUTHENTICATION_KEY, "anything")
-            .put(AuthenticationServiceField.RUN_AS_USER_HEADER, "anything")
-            .map();
+        Map<String, String> headers = Map.of(
+            AuthenticationField.AUTHENTICATION_KEY,
+            "anything",
+            AuthenticationServiceField.RUN_AS_USER_HEADER,
+            "anything"
+        );
 
         assertRunAsExecution(headers, h -> {
             assertThat(h.keySet(), hasSize(2));
@@ -316,7 +317,7 @@ public class ClientHelperTests extends ESTestCase {
             )
         );
         when(client.search(any())).thenReturn(searchFuture);
-        Map<String, String> unrelatedHeaders = MapBuilder.<String, String>newMapBuilder().put(randomAlphaOfLength(10), "anything").map();
+        Map<String, String> unrelatedHeaders = Map.of(randomAlphaOfLength(10), "anything");
 
         assertExecutionWithOrigin(unrelatedHeaders, client);
     }

+ 7 - 36
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ml/inference/preprocessing/MultiTests.java

@@ -6,7 +6,6 @@
  */
 package org.elasticsearch.xpack.core.ml.inference.preprocessing;
 
-import org.elasticsearch.common.collect.MapBuilder;
 import org.elasticsearch.common.io.stream.Writeable;
 import org.elasticsearch.xcontent.XContentParser;
 
@@ -84,19 +83,11 @@ public class MultiTests extends PreProcessingTests<Multi> {
     public void testReverseLookup() {
         String field = "text";
         NGram nGram = new NGram(field, Collections.singletonList(1), 0, 2, null, "f");
-        OneHotEncoding oneHotEncoding = new OneHotEncoding(
-            "f.10",
-            MapBuilder.<String, String>newMapBuilder().put("a", "has_a").put("b", "has_b").map(),
-            true
-        );
+        OneHotEncoding oneHotEncoding = new OneHotEncoding("f.10", Map.of("a", "has_a", "b", "has_b"), true);
         Multi multi = new Multi(new PreProcessor[] { nGram, oneHotEncoding }, true);
         assertThat(multi.reverseLookup(), allOf(hasEntry("has_a", field), hasEntry("has_b", field), hasEntry("f.11", field)));
 
-        OneHotEncoding oneHotEncodingOutside = new OneHotEncoding(
-            "some_other",
-            MapBuilder.<String, String>newMapBuilder().put("a", "has_3_a").put("b", "has_3_b").map(),
-            true
-        );
+        OneHotEncoding oneHotEncodingOutside = new OneHotEncoding("some_other", Map.of("a", "has_3_a", "b", "has_3_b"), true);
         multi = new Multi(new PreProcessor[] { nGram, oneHotEncoding, oneHotEncodingOutside }, true);
         expectThrows(IllegalArgumentException.class, multi::reverseLookup);
     }
@@ -104,16 +95,8 @@ public class MultiTests extends PreProcessingTests<Multi> {
     public void testProcessWithFieldPresent() {
         String field = "text";
         NGram nGram = new NGram(field, Collections.singletonList(1), 0, 2, null, "f");
-        OneHotEncoding oneHotEncoding1 = new OneHotEncoding(
-            "f.10",
-            MapBuilder.<String, String>newMapBuilder().put("a", "has_a").put("b", "has_b").map(),
-            true
-        );
-        OneHotEncoding oneHotEncoding2 = new OneHotEncoding(
-            "f.11",
-            MapBuilder.<String, String>newMapBuilder().put("a", "has_2_a").put("b", "has_2_b").map(),
-            true
-        );
+        OneHotEncoding oneHotEncoding1 = new OneHotEncoding("f.10", Map.of("a", "has_a", "b", "has_b"), true);
+        OneHotEncoding oneHotEncoding2 = new OneHotEncoding("f.11", Map.of("a", "has_2_a", "b", "has_2_b"), true);
         Multi multi = new Multi(new PreProcessor[] { nGram, oneHotEncoding1, oneHotEncoding2 }, true);
         Map<String, Object> fields = randomFieldValues("text", "cat");
         multi.process(fields);
@@ -126,21 +109,9 @@ public class MultiTests extends PreProcessingTests<Multi> {
     public void testInputOutputFields() {
         String field = "text";
         NGram nGram = new NGram(field, Collections.singletonList(1), 0, 3, null, "f");
-        OneHotEncoding oneHotEncoding1 = new OneHotEncoding(
-            "f.10",
-            MapBuilder.<String, String>newMapBuilder().put("a", "has_a").put("b", "has_b").map(),
-            true
-        );
-        OneHotEncoding oneHotEncoding2 = new OneHotEncoding(
-            "f.11",
-            MapBuilder.<String, String>newMapBuilder().put("a", "has_2_a").put("b", "has_2_b").map(),
-            true
-        );
-        OneHotEncoding oneHotEncoding3 = new OneHotEncoding(
-            "some_other",
-            MapBuilder.<String, String>newMapBuilder().put("a", "has_3_a").put("b", "has_3_b").map(),
-            true
-        );
+        OneHotEncoding oneHotEncoding1 = new OneHotEncoding("f.10", Map.of("a", "has_a", "b", "has_b"), true);
+        OneHotEncoding oneHotEncoding2 = new OneHotEncoding("f.11", Map.of("a", "has_2_a", "b", "has_2_b"), true);
+        OneHotEncoding oneHotEncoding3 = new OneHotEncoding("some_other", Map.of("a", "has_3_a", "b", "has_3_b"), true);
         Multi multi = new Multi(new PreProcessor[] { nGram, oneHotEncoding1, oneHotEncoding2, oneHotEncoding3 }, true);
         assertThat(multi.inputFields(), contains(field, "some_other"));
         assertThat(multi.outputFields(), contains("f.12", "has_a", "has_b", "has_2_a", "has_2_b", "has_3_a", "has_3_b"));