java.util.Collections.singleton()方法的使用及代码示例

x33g5p2x  于2022-01-16 转载在 其他  
字(13.5k)|赞(0)|评价(0)|浏览(257)

本文整理了Java中java.util.Collections.singleton()方法的一些代码示例,展示了Collections.singleton()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Collections.singleton()方法的具体详情如下:
包路径:java.util.Collections
类名称:Collections
方法名:singleton

Collections.singleton介绍

[英]Returns a set containing the specified element. The set cannot be modified. The set is serializable.
[中]返回包含指定元素的集合。无法修改该集合。该集合是可序列化的。

代码示例

代码示例来源:origin: spring-projects/spring-framework

private Set<String> getPrefixesSet(String namespaceUri) {
  Assert.notNull(namespaceUri, "No namespaceUri given");
  if (this.defaultNamespaceUri.equals(namespaceUri)) {
    return Collections.singleton(XMLConstants.DEFAULT_NS_PREFIX);
  }
  else if (XMLConstants.XML_NS_URI.equals(namespaceUri)) {
    return Collections.singleton(XMLConstants.XML_NS_PREFIX);
  }
  else if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(namespaceUri)) {
    return Collections.singleton(XMLConstants.XMLNS_ATTRIBUTE);
  }
  else {
    Set<String> prefixes = this.namespaceUriToPrefixes.get(namespaceUri);
    return (prefixes != null ?  Collections.unmodifiableSet(prefixes) : Collections.emptySet());
  }
}

代码示例来源:origin: redisson/redisson

private static Iterable<Class<?>> getClassHierarchy(Class<?> clazz) {
  // Don't descend into hierarchy for RObjects
  if (Arrays.asList(clazz.getInterfaces()).contains(RObject.class)) {
    return Collections.<Class<?>>singleton(clazz);
  }
  List<Class<?>> classes = new ArrayList<Class<?>>();
  for (Class<?> c = clazz; c != null; c = c.getSuperclass()) {
    classes.add(c);
  }
  return classes;
}

代码示例来源:origin: ReactiveX/RxJava

@Override
  public Iterable<Integer> apply(Integer v) {
    return v == 2 ? Collections.singleton(1) : Collections.<Integer>emptySet();
  }
})

代码示例来源:origin: apache/kafka

@Test
public void testOneConsumerNoTopic() {
  String consumerId = "consumer";
  Map<String, Integer> partitionsPerTopic = new HashMap<>();
  Map<String, List<TopicPartition>> assignment = assignor.assign(partitionsPerTopic,
      Collections.singletonMap(consumerId, new Subscription(Collections.<String>emptyList())));
  assertEquals(Collections.singleton(consumerId), assignment.keySet());
  assertTrue(assignment.get(consumerId).isEmpty());
}

代码示例来源:origin: aragozin/jvm-tools

private static void add(Map<PoolType, Collection<String>> map, PoolType type, String name) {
  if (map.containsKey(type)) {
    List<String> names = new ArrayList<String>();
    names.addAll(map.get(type));
    names.add(name);
    map.put(type, names);
  }
  else {
    map.put(type, Collections.singleton(name));
  }
}

代码示例来源:origin: wildfly/wildfly

private void parseServerConfig(final XMLExtendedStreamReader reader, final String name, final PathAddress parent, List<ModelNode> list) throws XMLStreamException {
  PathAddress address = parent.append(MailSubsystemModel.SERVER_TYPE, name);
  final ModelNode operation = Util.createAddOperation(address);
  list.add(operation);
  String socketBindingRef = null;
  for (int i = 0; i < reader.getAttributeCount(); i++) {
    String attr = reader.getAttributeLocalName(i);
    String value = reader.getAttributeValue(i);
    switch (attr) {
      case MailSubsystemModel.OUTBOUND_SOCKET_BINDING_REF:
        socketBindingRef = value;
        OUTBOUND_SOCKET_BINDING_REF.parseAndSetParameter(value, operation, reader);
        break;
      case MailSubsystemModel.SSL:
        SSL.parseAndSetParameter(value, operation, reader);
        break;
      case MailSubsystemModel.TLS:
        TLS.parseAndSetParameter(value, operation, reader);
        break;
      default:
        throw ParseUtils.unexpectedAttribute(reader, i);
    }
  }
  if (socketBindingRef == null) {
    throw ParseUtils.missingRequired(reader, Collections.singleton(OUTBOUND_SOCKET_BINDING_REF));
  }
  parseLogin(reader, operation);
}

代码示例来源:origin: redisson/redisson

/**
 * Extends this key by the given method description.
 *
 * @param methodDescription The method to extend this key with.
 * @param harmonizer        The harmonizer to use for determining method equality.
 * @return The harmonized key representing the extension of this key with the provided method.
 */
protected Harmonized<V> extend(MethodDescription.InDefinedShape methodDescription, Harmonizer<V> harmonizer) {
  Map<V, Set<MethodDescription.TypeToken>> identifiers = new HashMap<V, Set<MethodDescription.TypeToken>>(this.identifiers);
  MethodDescription.TypeToken typeToken = methodDescription.asTypeToken();
  V identifier = harmonizer.harmonize(typeToken);
  Set<MethodDescription.TypeToken> typeTokens = identifiers.get(identifier);
  if (typeTokens == null) {
    identifiers.put(identifier, Collections.singleton(typeToken));
  } else {
    typeTokens = new HashSet<MethodDescription.TypeToken>(typeTokens);
    typeTokens.add(typeToken);
    identifiers.put(identifier, typeTokens);
  }
  return new Harmonized<V>(internalName, parameterCount, identifiers);
}

代码示例来源:origin: OryxProject/oryx

private Map<Integer,Collection<String>> getDistinctValues(JavaRDD<String[]> parsedRDD) {
 int[] categoricalIndices = IntStream.range(0, inputSchema.getNumFeatures()).
   filter(inputSchema::isCategorical).toArray();
 return parsedRDD.mapPartitions(data -> {
   Map<Integer,Collection<String>> categoryValues = new HashMap<>();
   for (int i : categoricalIndices) {
    categoryValues.put(i, new HashSet<>());
   }
   data.forEachRemaining(datum ->
    categoryValues.forEach((category, values) -> values.add(datum[category]))
   );
   return Collections.singleton(categoryValues).iterator();
  }).reduce((v1, v2) -> {
   // Assumes both have the same key set
   v1.forEach((category, values) -> values.addAll(v2.get(category)));
   return v1;
  });
}

代码示例来源:origin: google/guava

public void testForMapAsMap() {
 Map<String, Integer> map = Maps.newHashMap();
 map.put("foo", 1);
 map.put("bar", 2);
 Map<String, Collection<Integer>> asMap = Multimaps.forMap(map).asMap();
 assertEquals(Collections.singleton(1), asMap.get("foo"));
 assertNull(asMap.get("cow"));
 assertTrue(asMap.containsKey("foo"));
 assertFalse(asMap.containsKey("cow"));
 Set<Entry<String, Collection<Integer>>> entries = asMap.entrySet();
 assertFalse(entries.contains((Object) 4.5));
 assertFalse(entries.remove((Object) 4.5));
 assertFalse(entries.contains(Maps.immutableEntry("foo", Collections.singletonList(1))));
 assertFalse(entries.remove(Maps.immutableEntry("foo", Collections.singletonList(1))));
 assertFalse(entries.contains(Maps.immutableEntry("foo", Sets.newLinkedHashSet(asList(1, 2)))));
 assertFalse(entries.remove(Maps.immutableEntry("foo", Sets.newLinkedHashSet(asList(1, 2)))));
 assertFalse(entries.contains(Maps.immutableEntry("foo", Collections.singleton(2))));
 assertFalse(entries.remove(Maps.immutableEntry("foo", Collections.singleton(2))));
 assertTrue(map.containsKey("foo"));
 assertTrue(entries.contains(Maps.immutableEntry("foo", Collections.singleton(1))));
 assertTrue(entries.remove(Maps.immutableEntry("foo", Collections.singleton(1))));
 assertFalse(map.containsKey("foo"));
}

代码示例来源:origin: apache/incubator-dubbo

private Set<String> getPackagesToScan(AnnotationMetadata metadata) {
  AnnotationAttributes attributes = AnnotationAttributes.fromMap(
      metadata.getAnnotationAttributes(DubboComponentScan.class.getName()));
  String[] basePackages = attributes.getStringArray("basePackages");
  Class<?>[] basePackageClasses = attributes.getClassArray("basePackageClasses");
  String[] value = attributes.getStringArray("value");
  // Appends value array attributes
  Set<String> packagesToScan = new LinkedHashSet<String>(Arrays.asList(value));
  packagesToScan.addAll(Arrays.asList(basePackages));
  for (Class<?> basePackageClass : basePackageClasses) {
    packagesToScan.add(ClassUtils.getPackageName(basePackageClass));
  }
  if (packagesToScan.isEmpty()) {
    return Collections.singleton(ClassUtils.getPackageName(metadata.getClassName()));
  }
  return packagesToScan;
}

代码示例来源:origin: spring-projects/spring-framework

/**
 * @since 4.3
 */
@Test
public void equalsWithSameContextCustomizers() {
  Set<ContextCustomizer> customizers = Collections.singleton(mock(ContextCustomizer.class));
  MergedContextConfiguration mergedConfig1 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY,
    EMPTY_CLASS_ARRAY, null, EMPTY_STRING_ARRAY, null, null, customizers, loader, null, null);
  MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY,
    EMPTY_CLASS_ARRAY, null, EMPTY_STRING_ARRAY, null, null, customizers, loader, null, null);
  assertEquals(mergedConfig1, mergedConfig2);
}

代码示例来源:origin: apache/kafka

@Test(expected = InvalidTopicException.class)
  public void testSubscriptionOnInvalidTopic() {
    Time time = new MockTime();
    Metadata metadata = createMetadata();
    MockClient client = new MockClient(time, metadata);

    initMetadata(client, Collections.singletonMap(topic, 1));
    Cluster cluster = metadata.fetch();

    PartitionAssignor assignor = new RoundRobinAssignor();

    String invalidTopicName = "topic abc";  // Invalid topic name due to space

    List<MetadataResponse.TopicMetadata> topicMetadata = new ArrayList<>();
    topicMetadata.add(new MetadataResponse.TopicMetadata(Errors.INVALID_TOPIC_EXCEPTION,
        invalidTopicName, false, Collections.emptyList()));
    MetadataResponse updateResponse = new MetadataResponse(cluster.nodes(),
        cluster.clusterResource().clusterId(),
        cluster.controller().id(),
        topicMetadata);
    client.prepareMetadataUpdate(updateResponse);

    KafkaConsumer<String, String> consumer = newConsumer(time, client, metadata, assignor, true);
    consumer.subscribe(singleton(invalidTopicName), getConsumerRebalanceListener(consumer));

    consumer.poll(Duration.ZERO);
  }
}

代码示例来源:origin: apache/kafka

@Test
public void testNoCoordinatorDiscoveryIfPositionsKnown() {
  assertTrue(coordinator.coordinatorUnknown());
  subscriptions.assignFromUser(singleton(t1p));
  subscriptions.seek(t1p, 500L);
  coordinator.refreshCommittedOffsetsIfNeeded(time.timer(Long.MAX_VALUE));
  assertEquals(Collections.emptySet(), subscriptions.missingFetchPositions());
  assertTrue(subscriptions.hasAllFetchPositions());
  assertEquals(500L, subscriptions.position(t1p).longValue());
  assertTrue(coordinator.coordinatorUnknown());
}

代码示例来源:origin: google/guava

public void testRowKeyMapTailMap() {
 sortedTable = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c');
 Map<String, Map<Integer, Character>> map = sortedTable.rowMap().tailMap("cat");
 assertEquals(1, map.size());
 assertEquals(ImmutableMap.of(1, 'a', 3, 'c'), map.get("foo"));
 map.clear();
 assertTrue(map.isEmpty());
 assertEquals(Collections.singleton("bar"), sortedTable.rowKeySet());
}

代码示例来源:origin: Netflix/eureka

public Set<String> getAllKnownRegions() {
  String localRegion = instanceRegionChecker.getLocalRegion();
  if (!remoteRegionVsApps.isEmpty()) {
    Set<String> regions = remoteRegionVsApps.keySet();
    Set<String> toReturn = new HashSet<String>(regions);
    toReturn.add(localRegion);
    return toReturn;
  } else {
    return Collections.singleton(localRegion);
  }
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void modelAttributesConventions() {
  Set<String> model = Collections.singleton("bar");
  Mono<RenderingResponse> result = RenderingResponse.create("foo")
      .modelAttributes(model).build();
  StepVerifier.create(result)
      .expectNextMatches(response -> "bar".equals(response.model().get("string")))
      .expectComplete()
      .verify();
}

代码示例来源:origin: google/guava

public void testForMapRemoveAll() {
 Map<String, Integer> map = Maps.newHashMap();
 map.put("foo", 1);
 map.put("bar", 2);
 map.put("cow", 3);
 Multimap<String, Integer> multimap = Multimaps.forMap(map);
 assertEquals(3, multimap.size());
 assertEquals(Collections.emptySet(), multimap.removeAll("dog"));
 assertEquals(3, multimap.size());
 assertTrue(multimap.containsKey("bar"));
 assertEquals(Collections.singleton(2), multimap.removeAll("bar"));
 assertEquals(2, multimap.size());
 assertFalse(multimap.containsKey("bar"));
}

代码示例来源:origin: apache/kafka

@Test
public void testClearBufferedDataForTopicPartitions() {
  subscriptions.assignFromUser(singleton(tp0));
  subscriptions.seek(tp0, 0);
  // normal fetch
  assertEquals(1, fetcher.sendFetches());
  assertFalse(fetcher.hasCompletedFetches());
  client.prepareResponse(fullFetchResponse(tp0, this.records, Errors.NONE, 100L, 0));
  consumerClient.poll(time.timer(0));
  assertTrue(fetcher.hasCompletedFetches());
  Set<TopicPartition> newAssignedTopicPartitions = new HashSet<>();
  newAssignedTopicPartitions.add(tp1);
  fetcher.clearBufferedDataForUnassignedPartitions(newAssignedTopicPartitions);
  assertFalse(fetcher.hasCompletedFetches());
}

代码示例来源:origin: ReactiveX/RxJava

@Test(timeout = 5000, expected = TestException.class)
public void mergeIterableOneThrows() {
  Completable c = Completable.merge(Collections.singleton(error.completable));
  c.blockingAwait();
}

代码示例来源:origin: org.mockito/mockito-core

private void assureCanReadMockito(Set<Class<?>> types) {
  if (redefineModule == null) {
    return;
  }
  Set<Object> modules = new HashSet<Object>();
  try {
    Object target = getModule.invoke(Class.forName("org.mockito.internal.creation.bytebuddy.inject.MockMethodDispatcher", false, null));
    for (Class<?> type : types) {
      Object module = getModule.invoke(type);
      if (!modules.contains(module) && !(Boolean) canRead.invoke(module, target)) {
        modules.add(module);
      }
    }
    for (Object module : modules) {
      redefineModule.invoke(instrumentation, module, Collections.singleton(target),
        Collections.emptyMap(), Collections.emptyMap(), Collections.emptySet(), Collections.emptyMap());
    }
  } catch (Exception e) {
    throw new IllegalStateException(join("Could not adjust module graph to make the mock instance dispatcher visible to some classes",
      "",
      "At least one of those modules: " + modules + " is not reading the unnamed module of the bootstrap loader",
      "Without such a read edge, the classes that are redefined to become mocks cannot access the mock dispatcher.",
      "To circumvent this, Mockito attempted to add a read edge to this module what failed for an unexpected reason"), e);
  }
}

相关文章

Collections类方法