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

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

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

Collections.singletonList介绍

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

代码示例

代码示例来源:origin: square/retrofit

@Override List<? extends Converter.Factory> defaultConverterFactories() {
 return Build.VERSION.SDK_INT >= 24
   ? singletonList(OptionalConverterFactory.INSTANCE)
   : Collections.<Converter.Factory>emptyList();
}

代码示例来源:origin: skylot/jadx

@SuppressWarnings("unchecked")
public static <T> List<T> lockList(List<T> list) {
  if (list.isEmpty()) {
    return Collections.emptyList();
  }
  if (list.size() == 1) {
    return Collections.singletonList(list.get(0));
  }
  return new ImmutableList<>(list);
}

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

@Override
public void prepare(WorkerTopologyContext context, GlobalStreamId stream, List<Integer> targetTasks) {
  this.targetTasks = new ArrayList<List<Integer>>();
  for (Integer targetTask : targetTasks) {
    this.targetTasks.add(Collections.singletonList(targetTask));
  }
  this.numTasks = targetTasks.size();
}

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

@Test
public void testGenericTypeNestingMapOfListOfListOfInteger() throws Exception {
  Map<String, List<List<String>>> map = new HashMap<>();
  List<String> list = Arrays.asList(new String[] {"1", "2", "3"});
  map.put("testKey", Collections.singletonList(list));
  NestedGenericCollectionBean gb = new NestedGenericCollectionBean();
  BeanWrapper bw = new BeanWrapperImpl(gb);
  bw.setPropertyValue("mapOfListOfListOfInteger", map);
  Object obj = gb.getMapOfListOfListOfInteger().get("testKey").get(0).get(0);
  assertTrue(obj instanceof Integer);
  assertEquals(1, ((Integer) obj).intValue());
}

代码示例来源:origin: org.kie.server/kie-server-client

@Override
public void unregisterQuery(String queryName) {
  if (config.isRest()) {
    Map<String, Object> valuesMap = new HashMap<String, Object>();
    valuesMap.put(QUERY_NAME, queryName);
    makeHttpDeleteRequestAndCreateCustomResponse(build(loadBalancer.getUrl(), QUERY_DEF_URI + "/" + DROP_QUERY_DEF_DELETE_URI, valuesMap), null);
  } else {
    CommandScript script = new CommandScript(Collections.singletonList((KieServerCommand) new DescriptorCommand("QueryDataService", "unregisterQuery", new Object[]{queryName})));
    ServiceResponse<?> response = (ServiceResponse<?>) executeJmsCommand(script, DescriptorCommand.class.getName(), "BPM").getResponses().get(0);
    throwExceptionOnFailure(response);
  }
}

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

/**
 * @param allowHeapAllocation whether or not to include heap allocation as an alternative.
 * @param additional other means of allocation to try after the standard off/on heap alternatives.
 * @return an array of {@link NumberArrayFactory} with the desired alternatives.
 */
static NumberArrayFactory[] allocationAlternatives( boolean allowHeapAllocation, NumberArrayFactory... additional )
{
  List<NumberArrayFactory> result = new ArrayList<>( Collections.singletonList( OFF_HEAP ) );
  if ( allowHeapAllocation )
  {
    result.add( HEAP );
  }
  result.addAll( asList( additional ) );
  return result.toArray( new NumberArrayFactory[result.size()] );
}

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

@Test
public void afterSessionInitialized() throws Exception {
  this.session.initializeDelegateSession(this.webSocketSession);
  assertEquals(Collections.singletonList(new TextMessage("o")), this.webSocketSession.getSentMessages());
  assertEquals(Arrays.asList("schedule"), this.session.heartbeatSchedulingEvents);
  verify(this.webSocketHandler).afterConnectionEstablished(this.session);
  verifyNoMoreInteractions(this.taskScheduler, this.webSocketHandler);
}

代码示例来源:origin: eclipse-vertx/vert.x

@Test
public void testArrayMapping() {
 JsonParser parser = JsonParser.newParser();
 List<Object> values = new ArrayList<>();
 parser.arrayValueMode();
 parser.handler(event -> values.add(event.mapTo(LinkedList.class)));
 parser.handle(new JsonArray().add(0).add(1).add(2).toBuffer());
 assertEquals(Collections.singletonList(Arrays.asList(0L, 1L, 2L)), values);
 assertEquals(LinkedList.class, values.get(0).getClass());
}

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

public void testPartition_1_1() {
 List<Integer> source = Collections.singletonList(1);
 List<List<Integer>> partitions = Lists.partition(source, 1);
 assertEquals(1, partitions.size());
 assertEquals(Collections.singletonList(1), partitions.get(0));
}

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

private void addTask(Runnable task, boolean successTask) {
  Assert.notNull(this.receiptId,
      "To track receipts, set autoReceiptEnabled=true or add 'receiptId' header");
  synchronized (this) {
    if (this.result != null && this.result == successTask) {
      invoke(Collections.singletonList(task));
    }
    else {
      if (successTask) {
        this.receiptCallbacks.add(task);
      }
      else {
        this.receiptLostCallbacks.add(task);
      }
    }
  }
}

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

@Test
public void jacksonJsonViewWithResponseBodyAndJsonMessageConverter() throws Exception {
  Method method = JacksonController.class.getMethod("handleResponseBody");
  HandlerMethod handlerMethod = new HandlerMethod(new JacksonController(), method);
  MethodParameter methodReturnType = handlerMethod.getReturnType();
  List<HttpMessageConverter<?>> converters = new ArrayList<>();
  converters.add(new MappingJackson2HttpMessageConverter());
  RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor(
      converters, null, Collections.singletonList(new JsonViewResponseBodyAdvice()));
  Object returnValue = new JacksonController().handleResponseBody();
  processor.handleReturnValue(returnValue, methodReturnType, this.container, this.request);
  String content = this.servletResponse.getContentAsString();
  assertFalse(content.contains("\"withView1\":\"with\""));
  assertTrue(content.contains("\"withView2\":\"with\""));
  assertFalse(content.contains("\"withoutView\":\"without\""));
}

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

public void testPartition_2_1() {
 List<Integer> source = asList(1, 2);
 List<List<Integer>> partitions = Lists.partition(source, 1);
 assertEquals(2, partitions.size());
 assertEquals(Collections.singletonList(1), partitions.get(0));
 assertEquals(Collections.singletonList(2), partitions.get(1));
}

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

@Test
public void testClassNamesToString() {
  List<Class<?>> ifcs = new LinkedList<>();
  ifcs.add(Serializable.class);
  ifcs.add(Runnable.class);
  assertEquals("[interface java.io.Serializable, interface java.lang.Runnable]", ifcs.toString());
  assertEquals("[java.io.Serializable, java.lang.Runnable]", ClassUtils.classNamesToString(ifcs));
  List<Class<?>> classes = new LinkedList<>();
  classes.add(LinkedList.class);
  classes.add(Integer.class);
  assertEquals("[class java.util.LinkedList, class java.lang.Integer]", classes.toString());
  assertEquals("[java.util.LinkedList, java.lang.Integer]", ClassUtils.classNamesToString(classes));
  assertEquals("[interface java.util.List]", Collections.singletonList(List.class).toString());
  assertEquals("[java.util.List]", ClassUtils.classNamesToString(List.class));
  assertEquals("[]", Collections.EMPTY_LIST.toString());
  assertEquals("[]", ClassUtils.classNamesToString(Collections.emptyList()));
}

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

public IndexMergerV9CompatibilityTest(SegmentWriteOutMediumFactory segmentWriteOutMediumFactory)
{
 indexMerger = TestHelper.getTestIndexMergerV9(segmentWriteOutMediumFactory);
 indexIO = TestHelper.getTestIndexIO();
 events = new ArrayList<>();
 final Map<String, Object> map1 = ImmutableMap.of(
   DIMS.get(0), ImmutableList.of("dim00", "dim01"),
   DIMS.get(1), "dim10"
 );
 final List<String> nullList = Collections.singletonList(null);
 final Map<String, Object> map2 = ImmutableMap.of(
   DIMS.get(0), nullList,
   DIMS.get(1), "dim10"
 );
 final Map<String, Object> map3 = ImmutableMap.of(
   DIMS.get(0),
   ImmutableList.of("dim00", "dim01")
 );
 final Map<String, Object> map4 = ImmutableMap.of();
 final Map<String, Object> map5 = ImmutableMap.of(DIMS.get(1), "dim10");
 final Map<String, Object> map6 = new HashMap<>();
 map6.put(DIMS.get(1), null); // ImmutableMap cannot take null
 int i = 0;
 for (final Map<String, Object> map : Arrays.asList(map1, map2, map3, map4, map5, map6)) {
  events.add(new MapBasedInputRow(TIMESTAMP + i++, DIMS, map));
 }
}

代码示例来源:origin: SonarSource/sonarqube

private String responseTypeFullyQualified(String path, String action) {
 String fullPath = path + "/" + action;
 List<String[]> responseTypesConfig = responseTypes.get(fullPath);
 String fullyQualified;
 if (responseTypesConfig == null) {
  fullyQualified = guessResponseType(path, action);
  responseTypes.put(fullPath, Collections.singletonList(new String[] {fullPath, fullyQualified}));
 } else {
  fullyQualified = responseTypesConfig.get(0)[1];
 }
 return fullyQualified;
}

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

@Test
public void convertCollectionToObject() {
  List<Long> list = Collections.singletonList(3L);
  Long result = conversionService.convert(list, Long.class);
  assertEquals(Long.valueOf(3), result);
}

代码示例来源:origin: JakeWharton/butterknife

@Test public void humanDescriptionJoinWorks() {
 MemberViewBinding one = new TestViewBinding("one");
 MemberViewBinding two = new TestViewBinding("two");
 MemberViewBinding three = new TestViewBinding("three");
 String result1 = asHumanDescription(singletonList(one));
 assertThat(result1).isEqualTo("one");
 String result2 = asHumanDescription(asList(one, two));
 assertThat(result2).isEqualTo("one and two");
 String result3 = asHumanDescription(asList(one, two, three));
 assertThat(result3).isEqualTo("one, two, and three");
}

代码示例来源:origin: skylot/jadx

@Test
public void testHierarchyPackages() {
  String pkgName = "a.b.c.d.e";
  List<JavaPackage> packages = Collections.singletonList(newPkg(pkgName));
  List<JPackage> out = sources.getHierarchyPackages(packages);
  assertThat(out, hasSize(1));
  JPackage jPkg = out.get(0);
  assertThat(jPkg.getName(), is(pkgName));
  assertThat(jPkg.getClasses(), hasSize(1));
}

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

@CollectionSize.Require(absent = {ZERO, ONE})
public void testSubList_ofSubListNonEmpty() {
 List<E> subList = getList().subList(0, 2).subList(1, 2);
 assertEquals(
   "subList(0, 2).subList(1, 2) "
     + "should be a single-element list of the element at index 1",
   Collections.singletonList(getOrderedElements().get(1)),
   subList);
}

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

@Test
public void assertValueSequenceOnlyThrowsOnUnexpectedValue() {
  TestObserver<Integer> to = TestObserver.create();
  to.onSubscribe(Disposables.empty());
  to.assertValueSequenceOnly(Collections.<Integer>emptyList());
  to.onNext(5);
  to.assertValueSequenceOnly(Collections.singletonList(5));
  to.onNext(-1);
  try {
    to.assertValueSequenceOnly(Collections.singletonList(5));
    throw new RuntimeException();
  } catch (AssertionError ex) {
    // expected
  }
}

相关文章

微信公众号

最新文章

更多

Collections类方法