java.util.Collection.toArray()方法的使用及代码示例

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

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

Collection.toArray介绍

[英]Returns a new array containing all elements contained in this Collection. If the implementation has ordered elements it will return the element array in the same order as an iterator would return them. The array returned does not reflect any changes of the Collection. A new array is created even if the underlying data structure is already an array.
[中]返回包含此集合中包含的所有元素的新数组。如果实现对元素进行了排序,它将以迭代器返回元素数组的相同顺序返回元素数组。返回的数组不反映集合的任何更改。即使基础数据结构已经是一个数组,也会创建一个新数组。

代码示例

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

private static Type[] toArray(Collection<Type> types) {
 return types.toArray(new Type[types.size()]);
}

代码示例来源:origin: hankcs/HanLP

@Override
public <T> T[] toArray(T[] a)
{
  return termFrequencyMap.values().toArray(a);
}

代码示例来源:origin: jenkinsci/jenkins

/**
 * Gets the read-only list of all {@link Computer}s.
 */
public Computer[] getComputers() {
  Computer[] r = computers.values().toArray(new Computer[computers.size()]);
  Arrays.sort(r,new Comparator<Computer>() {
    @Override public int compare(Computer lhs, Computer rhs) {
      if(lhs.getNode()==Jenkins.this)  return -1;
      if(rhs.getNode()==Jenkins.this)  return 1;
      return lhs.getName().compareTo(rhs.getName());
    }
  });
  return r;
}

代码示例来源:origin: peter-lawrey/Java-Chronicle

public void add(String name, Wrapper wrapper) {
  wrappers.put(name, wrapper);
  wrappersArray = wrappers.values().toArray(new Wrapper[wrappers.size()]);
}

代码示例来源:origin: Bilibili/DanmakuFlameMaster

public void registerFilter(BaseDanmakuFilter filter) {
  filters.put(TAG_PRIMARY_CUSTOM_FILTER + "_" + filter.hashCode(), filter);
  mFilterArray = filters.values().toArray(mFilterArray);
}

代码示例来源:origin: commons-io/commons-io

new WildcardFileFilter("*"));
final int count = files.size();
final Object[] fileObjs = files.toArray();
assertEquals(fileNames.length, files.size());
  for (int j = 0; !found && j < fileNames.length; ++j) {
    if (fileNames[j].equals(((File) fileObjs[i]).getName())) {
      foundFileNames.put(fileNames[j], fileNames[j]);
      found = true;
assertEquals(foundFileNames.size(), fileNames.length);

代码示例来源:origin: lettuce-io/lettuce-core

@SuppressWarnings("unchecked")
private <T> T[] toArray(Collection<T> c) {
  Class<T> cls = (Class<T>) c.iterator().next().getClass();
  T[] array = (T[]) Array.newInstance(cls, c.size());
  return c.toArray(array);
}

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

/**
 * @since 4.2
 */
public Language[] all() {
 Collection<Language> languages = map.values();
 return languages.toArray(new Language[languages.size()]);
}

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

private static Map<Direction, RelationshipType[]> toTypeMap(
    Map<Direction, Collection<RelationshipType>> tempMap )
{
  // Remove OUT/IN where there is a BOTH
  Collection<RelationshipType> both = tempMap.get( Direction.BOTH );
  tempMap.get( Direction.OUTGOING ).removeAll( both );
  tempMap.get( Direction.INCOMING ).removeAll( both );
  // Convert into a final map
  Map<Direction, RelationshipType[]> map = new EnumMap<>( Direction.class );
  for ( Map.Entry<Direction, Collection<RelationshipType>> entry : tempMap.entrySet() )
  {
    if ( !entry.getValue().isEmpty() )
    {
      map.put( entry.getKey(), entry.getValue().toArray( new RelationshipType[entry.getValue().size()] ) );
    }
  }
  return map;
}

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

static <E> ImmutableMultiset<E> create(Collection<? extends Entry<? extends E>> entries) {
 @SuppressWarnings("unchecked")
 Entry<E>[] entriesArray = entries.toArray(new Entry[0]);
 Map<E, Integer> delegateMap = Maps.newHashMapWithExpectedSize(entriesArray.length);
 long size = 0;
 for (int i = 0; i < entriesArray.length; i++) {
  Entry<E> entry = entriesArray[i];
  int count = entry.getCount();
  size += count;
  E element = checkNotNull(entry.getElement());
  delegateMap.put(element, count);
  if (!(entry instanceof Multisets.ImmutableEntry)) {
   entriesArray[i] = Multisets.immutableEntry(element, count);
  }
 }
 return new JdkBackedImmutableMultiset<>(
   delegateMap, ImmutableList.asImmutableList(entriesArray), size);
}

代码示例来源:origin: stackoverflow.com

public static void copyBeanProperties(
  final Object source,
  final Object target,
  final Collection<String> includes){

  final Collection<String> excludes = new ArrayList<String>();
  final PropertyDescriptor[] propertyDescriptors =
    BeanUtils.getPropertyDescriptors(source.getClass());
  for(final PropertyDescriptor propertyDescriptor : propertyDescriptors){
    String propName = propertyDescriptor.getName();
    if(!includes.contains(propName)){
      excludes.add(propName);
    }
  }
  BeanUtils.copyProperties(
    source, target, excludes.toArray(new String[excludes.size()]));
}

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

/**
 * @param c Closure.
 */
public static GridResourceField[] toArray(Collection<GridResourceField> c) {
  if (c.isEmpty())
    return EMPTY_ARRAY;
  return c.toArray(new GridResourceField[c.size()]);
}

代码示例来源:origin: alibaba/druid

@Override
public DataSource get() {
  Map<String, DataSource> dataSourceMap = getDataSourceMap();
  if (dataSourceMap == null || dataSourceMap.isEmpty()) {
    return null;
  }
  Collection<DataSource> targetDataSourceSet;
  if (blacklist == null || blacklist.isEmpty() || blacklist.size() >= dataSourceMap.size()) {
    targetDataSourceSet = dataSourceMap.values();
  } else {
    targetDataSourceSet = new HashSet<DataSource>(dataSourceMap.values());
    for (DataSource b : blacklist) {
      targetDataSourceSet.remove(b);
    }
  }
  DataSource[] dataSources = targetDataSourceSet.toArray(new DataSource[] {});
  if (dataSources != null && dataSources.length > 0) {
    return dataSources[random.nextInt(targetDataSourceSet.size())];
  }
  return null;
}

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

@Test
public void testGroupByWithElementSelector() {
  Observable<String> source = Observable.just("one", "two", "three", "four", "five", "six");
  Observable<GroupedObservable<Integer, Integer>> grouped = source.groupBy(length, length);
  Map<Integer, Collection<Integer>> map = toMap(grouped);
  assertEquals(3, map.size());
  assertArrayEquals(Arrays.asList(3, 3, 3).toArray(), map.get(3).toArray());
  assertArrayEquals(Arrays.asList(4, 4).toArray(), map.get(4).toArray());
  assertArrayEquals(Arrays.asList(5).toArray(), map.get(5).toArray());
}

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

@Override
public Collection<V> create(Object... elements) {
 @SuppressWarnings("unchecked")
 V[] valuesArray = (V[]) elements;
 // Start with a suitably shaped collection of entries
 Collection<Entry<K, V>> originalEntries = mapGenerator.getSampleElements(elements.length);
 // Create a copy of that, with the desired value for each value
 Collection<Entry<K, V>> entries = new ArrayList<>(elements.length);
 int i = 0;
 for (Entry<K, V> entry : originalEntries) {
  entries.add(Helpers.mapEntry(entry.getKey(), valuesArray[i++]));
 }
 return mapGenerator.create(entries.toArray()).values();
}

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

@Override
public Set<K> create(Object... elements) {
 @SuppressWarnings("unchecked")
 K[] keysArray = (K[]) elements;
 // Start with a suitably shaped collection of entries
 Collection<Entry<K, V>> originalEntries = mapGenerator.getSampleElements(elements.length);
 // Create a copy of that, with the desired value for each key
 Collection<Entry<K, V>> entries = new ArrayList<>(elements.length);
 int i = 0;
 for (Entry<K, V> entry : originalEntries) {
  entries.add(Helpers.mapEntry(keysArray[i++], entry.getValue()));
 }
 return mapGenerator.create(entries.toArray()).keySet();
}

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

/**
 * Parse insert values.
 *
 * @param insertStatement insert statement
 */
public void parse(final InsertStatement insertStatement) {
  Collection<Keyword> valueKeywords = new LinkedList<>();
  valueKeywords.add(DefaultKeyword.VALUES);
  valueKeywords.addAll(Arrays.asList(getSynonymousKeywordsForValues()));
  if (lexerEngine.skipIfEqual(valueKeywords.toArray(new Keyword[valueKeywords.size()]))) {
    parseValues(insertStatement);
  }
}

代码示例来源:origin: ben-manes/caffeine

/**
 * Returns a future that waits for all of the dependent futures to complete and returns the
 * combined mapping if successful. If any future fails then it is automatically removed from
 * the cache if still present.
 */
private CompletableFuture<Map<K, V>> composeResult(Map<K, CompletableFuture<V>> futures) {
 if (futures.isEmpty()) {
  return CompletableFuture.completedFuture(Collections.emptyMap());
 }
 @SuppressWarnings("rawtypes")
 CompletableFuture<?>[] array = futures.values().toArray(new CompletableFuture[0]);
 return CompletableFuture.allOf(array).thenApply(ignored -> {
  Map<K, V> result = new LinkedHashMap<>(futures.size());
  futures.forEach((key, future) -> {
   V value = future.getNow(null);
   if (value != null) {
    result.put(key, value);
   }
  });
  return Collections.unmodifiableMap(result);
 });
}

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

private Annotation[] resolveAnnotations() {
  Annotation[] annotations = annotationCache.get(this);
  if (annotations == null) {
    Map<Class<? extends Annotation>, Annotation> annotationMap = new LinkedHashMap<>();
    addAnnotationsToMap(annotationMap, getReadMethod());
    addAnnotationsToMap(annotationMap, getWriteMethod());
    addAnnotationsToMap(annotationMap, getField());
    annotations = annotationMap.values().toArray(new Annotation[0]);
    annotationCache.put(this, annotations);
  }
  return annotations;
}

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

someMap.put(new TypedStringValue("key${age}"), new TypedStringValue("${age}"));
someMap.put(new TypedStringValue("key${age}ref"), new RuntimeBeanReference("${ref}"));
someMap.put("key1", new RuntimeBeanReference("${ref}"));
someMap.put("key2", "${age}name");
MutablePropertyValues innerPvs = new MutablePropertyValues();
assertEquals("myvarname98", tb2.getName());
assertEquals(tb2, tb1.getSpouse());
assertEquals(1, tb1.getSomeMap().size());
assertEquals("myValue", tb1.getSomeMap().get("myKey"));
assertEquals(2, tb2.getStringArray().length);
assertEquals(System.getProperty("os.name"), tb2.getStringArray()[0]);
assertEquals("98", tb2.getStringArray()[1]);
assertEquals(2, tb2.getFriends().size());
assertEquals("na98me", tb2.getFriends().iterator().next());
assertEquals(tb2, tb2.getFriends().toArray()[1]);
assertEquals(3, tb2.getSomeSet().size());
assertTrue(tb2.getSomeSet().contains("na98me"));
assertTrue(tb2.getSomeSet().contains(tb2));
assertTrue(tb2.getSomeSet().contains(new Integer(98)));
assertEquals(6, tb2.getSomeMap().size());
assertEquals("98", tb2.getSomeMap().get("key98"));
assertEquals(tb2, tb2.getSomeMap().get("key98ref"));

相关文章