Tabnine Logo
Collections.singleton
Code IndexAdd Tabnine to your IDE (free)

How to use
singleton
method
in
java.util.Collections

Best Java code snippets using java.util.Collections.singleton (Showing top 20 results out of 74,124)

Refine searchRefine arrow

  • Test.<init>
  • Collections.emptySet
  • List.add
  • Set.add
  • Assert.assertEquals
  • Map.get
  • Map.put
  • ParseUtils.missingRequired
  • XMLExtendedStreamReader.getAttributeValue
  • XMLExtendedStreamReader.getAttributeCount
  • Assert.assertTrue
  • XMLExtendedStreamReader.getAttributeLocalName
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);
  }
}
java.utilCollectionssingleton

Javadoc

Returns a set containing the specified element. The set cannot be modified. The set is serializable.

Popular methods of Collections

  • emptyList
    Returns the empty list (immutable). This list is serializable.This example illustrates the type-safe
  • sort
  • singletonList
    Returns an immutable list containing only the specified object. The returned list is serializable.
  • unmodifiableList
    Returns an unmodifiable view of the specified list. This method allows modules to provide users with
  • emptyMap
    Returns the empty map (immutable). This map is serializable.This example illustrates the type-safe w
  • emptySet
    Returns the empty set (immutable). This set is serializable. Unlike the like-named field, this metho
  • unmodifiableMap
    Returns an unmodifiable view of the specified map. This method allows modules to provide users with
  • unmodifiableSet
    Returns an unmodifiable view of the specified set. This method allows modules to provide users with
  • singletonMap
    Returns an immutable map, mapping only the specified key to the specified value. The returned map is
  • addAll
    Adds all of the specified elements to the specified collection. Elements to be added may be specifie
  • reverse
    Reverses the order of the elements in the specified list. This method runs in linear time.
  • unmodifiableCollection
    Returns an unmodifiable view of the specified collection. This method allows modules to provide user
  • reverse,
  • unmodifiableCollection,
  • shuffle,
  • enumeration,
  • list,
  • synchronizedMap,
  • synchronizedList,
  • reverseOrder,
  • emptyIterator

Popular in Java

  • Making http requests using okhttp
  • scheduleAtFixedRate (ScheduledExecutorService)
  • onCreateOptionsMenu (Activity)
  • getExternalFilesDir (Context)
  • EOFException (java.io)
    Thrown when a program encounters the end of a file or stream during an input operation.
  • FileOutputStream (java.io)
    An output stream that writes bytes to a file. If the output file exists, it can be replaced or appen
  • Runnable (java.lang)
    Represents a command that can be executed. Often used to run code in a different Thread.
  • UnknownHostException (java.net)
    Thrown when a hostname can not be resolved.
  • BitSet (java.util)
    The BitSet class implements abit array [http://en.wikipedia.org/wiki/Bit_array]. Each element is eit
  • CountDownLatch (java.util.concurrent)
    A synchronization aid that allows one or more threads to wait until a set of operations being perfor
  • Top Sublime Text plugins
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now