Java Code Examples for java.util.List.toArray()

The following are Jave code examples for showing how to use toArray() of the java.util.List class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: OpenJSharp   File: AnnotationSupport.java   View Source Code Vote up 6 votes
/**
 * Finds and returns all annotations in {@code annotations} matching
 * the given {@code annoClass}.
 *
 * Apart from annotations directly present in {@code annotations} this
 * method searches for annotations inside containers i.e. indirectly
 * present annotations.
 *
 * The order of the elements in the array returned depends on the iteration
 * order of the provided map. Specifically, the directly present annotations
 * come before the indirectly present annotations if and only if the
 * directly present annotations come before the indirectly present
 * annotations in the map.
 *
 * @param annotations the {@code Map} in which to search for annotations
 * @param annoClass the type of annotation to search for
 *
 * @return an array of instances of {@code annoClass} or an empty
 *         array if none were found
 */
public static <A extends Annotation> A[] getDirectlyAndIndirectlyPresent(
        Map<Class<? extends Annotation>, Annotation> annotations,
        Class<A> annoClass) {
    List<A> result = new ArrayList<A>();

    @SuppressWarnings("unchecked")
    A direct = (A) annotations.get(annoClass);
    if (direct != null)
        result.add(direct);

    A[] indirect = getIndirectlyPresent(annotations, annoClass);
    if (indirect != null && indirect.length != 0) {
        boolean indirectFirst = direct == null ||
                                containerBeforeContainee(annotations, annoClass);

        result.addAll((indirectFirst ? 0 : 1), Arrays.asList(indirect));
    }

    @SuppressWarnings("unchecked")
    A[] arr = (A[]) Array.newInstance(annoClass, result.size());
    return result.toArray(arr);
}
 
Example 2
Project: elasticsearch_my   File: IndicesAliasesRequest.java   View Source Code Vote up 6 votes
public String[] concreteAliases(MetaData metaData, String concreteIndex) {
    if (expandAliasesWildcards()) {
        //for DELETE we expand the aliases
        String[] indexAsArray = {concreteIndex};
        ImmutableOpenMap<String, List<AliasMetaData>> aliasMetaData = metaData.findAliases(aliases, indexAsArray);
        List<String> finalAliases = new ArrayList<>();
        for (ObjectCursor<List<AliasMetaData>> curAliases : aliasMetaData.values()) {
            for (AliasMetaData aliasMeta: curAliases.value) {
                finalAliases.add(aliasMeta.alias());
            }
        }
        return finalAliases.toArray(new String[finalAliases.size()]);
    } else {
        //for add we just return the current aliases
        return aliases;
    }
}
 
Example 3
Project: QLExpress   File: ExpressParse.java   View Source Code Vote up 6 votes
protected  Word[] dealInclude(Word[] wordObjects) throws Exception{
    boolean isInclude = false;
    StringBuffer includeFileName = new StringBuffer();
    int point = 0;
    List<Word> result = new ArrayList<Word>();
    while(point <wordObjects.length ){
      if(wordObjects[point].word.equals("include") ==true){
    	  isInclude = true;
    	  includeFileName.setLength(0);
      }else if(isInclude == true && wordObjects[point].word.equals(";") ==true) {
    	  isInclude = false;
    	  Word[] childExpressWord = this.getExpressByName(includeFileName.toString());
    	  childExpressWord = this.dealInclude(childExpressWord);
    	  for(int i=0;i< childExpressWord.length;i++){
    		  result.add(childExpressWord[i]);
    	  }
      }else if(isInclude == true){
    	  includeFileName.append(wordObjects[point].word);
      }else{
    	  result.add(wordObjects[point]);
      }
      point = point + 1;
    }
    return result.toArray(new Word[0]);
}
 
Example 4
Project: android_camera_experiment   File: Camera1Activity.java   View Source Code Vote up 6 votes
@Override
protected CharSequence[] getVideoQualityOptions() {
    List<CharSequence> videoQualities = new ArrayList<>();

    if (getMinimumVideoDuration() > 0)
        videoQualities.add(new VideoQualityOption(CameraConfiguration.MEDIA_QUALITY_AUTO, CameraHelper.getCamcorderProfile(CameraConfiguration.MEDIA_QUALITY_AUTO, getCameraController().getCurrentCameraId()), getMinimumVideoDuration()));

    CamcorderProfile camcorderProfile = CameraHelper.getCamcorderProfile(CameraConfiguration.MEDIA_QUALITY_HIGH, getCameraController().getCurrentCameraId());
    double videoDuration = CameraHelper.calculateApproximateVideoDuration(camcorderProfile, getVideoFileSize());
    videoQualities.add(new VideoQualityOption(CameraConfiguration.MEDIA_QUALITY_HIGH, camcorderProfile, videoDuration));

    camcorderProfile = CameraHelper.getCamcorderProfile(CameraConfiguration.MEDIA_QUALITY_MEDIUM, getCameraController().getCurrentCameraId());
    videoDuration = CameraHelper.calculateApproximateVideoDuration(camcorderProfile, getVideoFileSize());
    videoQualities.add(new VideoQualityOption(CameraConfiguration.MEDIA_QUALITY_MEDIUM, camcorderProfile, videoDuration));

    camcorderProfile = CameraHelper.getCamcorderProfile(CameraConfiguration.MEDIA_QUALITY_LOW, getCameraController().getCurrentCameraId());
    videoDuration = CameraHelper.calculateApproximateVideoDuration(camcorderProfile, getVideoFileSize());
    videoQualities.add(new VideoQualityOption(CameraConfiguration.MEDIA_QUALITY_LOW, camcorderProfile, videoDuration));

    CharSequence[] array = new CharSequence[videoQualities.size()];
    videoQualities.toArray(array);

    return array;
}
 
Example 5
Project: BetterBeginningsReborn   File: BrickOvenShapedRecipe.java   View Source Code Vote up 5 votes
@Override
public RecipeElement[] getInputs()
{
	List<RecipeElement> buf = new ArrayList<>();
	for (RecipeElement ore : recipeItems)
	{
		if (ore != null)
		{
			buf.add(ore);
		}
	}

	return buf.toArray(new RecipeElement[0]);
}
 
Example 6
Project: CustomWorldGen   File: Cartesian.java   View Source Code Vote up 5 votes
private static <T> T[] toArray(Class <? super T > clazz, Iterable <? extends T > it)
{
    List<T> list = Lists.<T>newArrayList();

    for (T t : it)
    {
        list.add(t);
    }

    return (T[])((Object[])list.toArray(createArray(clazz, list.size())));
}
 
Example 7
Project: OpenJSharp   File: TabularDataSupport.java   View Source Code Vote up 5 votes
/**
 * Creates an empty <tt>TabularDataSupport</tt> instance whose open-type is <var>tabularType</var>,
 * and whose underlying <tt>HashMap</tt> has the specified initial capacity and load factor.
 *
 * @param  tabularType               the <i>tabular type</i> describing this <tt>TabularData</tt> instance;
 *                           cannot be null.
 *
 * @param  initialCapacity   the initial capacity of the HashMap.
 *
 * @param  loadFactor        the load factor of the HashMap
 *
 * @throws IllegalArgumentException  if the initial capacity is less than zero,
 *                                   or the load factor is nonpositive,
 *                                   or the tabular type is null.
 */
public TabularDataSupport(TabularType tabularType, int initialCapacity, float loadFactor) {

    // Check tabularType is not null
    //
    if (tabularType == null) {
        throw new IllegalArgumentException("Argument tabularType cannot be null.");
    }

    // Initialize this.tabularType (and indexNamesArray for convenience)
    //
    this.tabularType = tabularType;
    List<String> tmpNames = tabularType.getIndexNames();
    this.indexNamesArray = tmpNames.toArray(new String[tmpNames.size()]);

    // Since LinkedHashMap was introduced in SE 1.4, it's conceivable even
    // if very unlikely that we might be the server of a 1.3 client.  In
    // that case you'll need to set this property.  See CR 6334663.
    String useHashMapProp = AccessController.doPrivileged(
            new GetPropertyAction("jmx.tabular.data.hash.map"));
    boolean useHashMap = "true".equalsIgnoreCase(useHashMapProp);

    // Construct the empty contents HashMap
    //
    this.dataMap = useHashMap ?
        new HashMap<Object,CompositeData>(initialCapacity, loadFactor) :
        new LinkedHashMap<Object, CompositeData>(initialCapacity, loadFactor);
}
 
Example 8
Project: jaffa-framework   File: PolicyManager.java   View Source Code Vote up 5 votes
/** Get the list of Role names that have access to the specified component
 * @param componentName The component name to get the roles for
 * @return Returns an array of Strings, each entry is a role name.
 *         If no roles have access to the component an empty array (new String[] {}) will be returned,
 *         If all roles have access to the component 'null' will be returned
 * @throws SecurityException if the component is invalid
 */
public static String[] getRolesForComponent(String componentName) {
    Map<String, List<String>> index = getComponentRoleIndex();
    if (index == null)
        return null;

    // Throw an exception if there is no entry for the component. This would mean an invalid component.
    if (!index.containsKey(componentName))
        throw new SecurityException("PolicyManager could not find component '" + componentName + "'");

    // Convert the extracted list to an array
    List<String> l = index.get(componentName);
    return l != null ? l.toArray(new String[l.size()]) : null;
}
 
Example 9
Project: MOAAP   File: MatOfFloat6.java   View Source Code Vote up 5 votes
public void fromList(List<Float> lb) {
    if(lb==null || lb.size()==0)
        return;
    Float ab[] = lb.toArray(new Float[0]);
    float a[] = new float[ab.length];
    for(int i=0; i<ab.length; i++)
        a[i] = ab[i];
    fromArray(a);
}
 
Example 10
Project: lams   File: ProcedureCallImpl.java   View Source Code Vote up 5 votes
/**
 * Collects any parameter registrations which indicate a REF_CURSOR parameter type/mode.
 *
 * @return The collected REF_CURSOR type parameters.
 */
public ParameterRegistrationImplementor[] collectRefCursorParameters() {
	final List<ParameterRegistrationImplementor> refCursorParams = new ArrayList<ParameterRegistrationImplementor>();
	for ( ParameterRegistrationImplementor param : registeredParameters ) {
		if ( param.getMode() == ParameterMode.REF_CURSOR ) {
			refCursorParams.add( param );
		}
	}
	return refCursorParams.toArray( new ParameterRegistrationImplementor[refCursorParams.size()] );
}
 
Example 11
Project: es-sql   File: WhereParser.java   View Source Code Vote up 5 votes
private Object[] getMethodValuesWithSubQueries(SQLMethodInvokeExpr method) throws SqlParseException {
    List<Object> values = new ArrayList<>();
    for (SQLExpr innerExpr : method.getParameters()) {
        if (innerExpr instanceof SQLQueryExpr) {
            Select select = sqlParser.parseSelect((MySqlSelectQueryBlock) ((SQLQueryExpr) innerExpr).getSubQuery().getQuery());
            values.add(new SubQueryExpression(select));
        } else if (innerExpr instanceof SQLTextLiteralExpr) {
            values.add(((SQLTextLiteralExpr) innerExpr).getText());
        } else {
            values.add(innerExpr);
        }

    }
    return values.toArray();
}
 
Example 12
Project: googles-monorepo-demo   File: Hashing.java   View Source Code Vote up 5 votes
/**
 * Returns a hash function which computes its hash code by concatenating the hash codes of the
 * underlying hash functions together. This can be useful if you need to generate hash codes of a
 * specific length.
 *
 * <p>For example, if you need 1024-bit hash codes, you could join two {@link Hashing#sha512} hash
 * functions together: {@code Hashing.concatenating(Hashing.sha512(), Hashing.sha512())}.
 *
 * @since 19.0
 */
public static HashFunction concatenating(Iterable<HashFunction> hashFunctions) {
  checkNotNull(hashFunctions);
  // We can't use Iterables.toArray() here because there's no hash->collect dependency
  List<HashFunction> list = new ArrayList<HashFunction>();
  for (HashFunction hashFunction : hashFunctions) {
    list.add(hashFunction);
  }
  checkArgument(list.size() > 0, "number of hash functions (%s) must be > 0", list.size());
  return new ConcatenatedHashFunction(list.toArray(new HashFunction[0]));
}
 
Example 13
Project: Equella   File: ToolsServiceImpl.java   View Source Code Vote up 5 votes
@Override
public String[] getCacheList(String ssid, String lastUpdate)
{
	try
	{
		authenticate(ssid);
		final List<String> l = remoteCachingService.getCacheList(lastUpdate);
		return l.toArray(new String[l.size()]);
	}
	catch( final Exception ex )
	{
		throw new RuntimeException(ex);
	}
}
 
Example 14
Project: NBANDROID-V2   File: EmulatorDeviceNode.java   View Source Code Vote up 4 votes
@Override
public Action[] getActions(boolean context) {
    List<? extends Action> actionsForPath = Utilities.actionsForPath("Android/ADB/EmulatorDevice");
    return actionsForPath.toArray(new Action[actionsForPath.size()]);
}
 
Example 15
Project: aos-FileCoreLibrary   File: FTPListParseEngine.java   View Source Code Vote up 4 votes
/**
 * Returns an array of FTPFile objects containing the whole list of
 * files returned by the server as read by this object's parser.
 * The files are filtered before being added to the array.
 *
 * @param filter FTPFileFilter, must not be <code>null</code>.
 *
 * @return an array of FTPFile objects containing the whole list of
 *         files returned by the server as read by this object's parser.
 * <p><b>
 * NOTE:</b> This array may contain null members if any of the
 * individual file listings failed to parse.  The caller should
 * check each entry for null before referencing it, or use the
 * a filter such as {@link org.apache.commons.net.ftp.FTPFileFilters#NON_NULL} which does not
 * allow null entries.
 * @since 2.2
 * @exception java.io.IOException - not ever thrown, may be removed in a later release
 */
public FTPFile[] getFiles(FTPFileFilter filter)
throws IOException // TODO remove; not actually thrown
{
    List<FTPFile> tmpResults = new ArrayList<FTPFile>();
    Iterator<String> iter = this.entries.iterator();
    while (iter.hasNext()) {
        String entry = iter.next();
        FTPFile temp = this.parser.parseFTPEntry(entry);
        if (filter.accept(temp)){
            tmpResults.add(temp);
        }
    }
    return tmpResults.toArray(new FTPFile[tmpResults.size()]);

}
 
Example 16
Project: elasticsearch_my   File: SnapshotShardsService.java   View Source Code Vote up 4 votes
@Override
public ClusterTasksResult<UpdateIndexShardSnapshotStatusRequest> execute(ClusterState currentState, List<UpdateIndexShardSnapshotStatusRequest> tasks) throws Exception {
    final SnapshotsInProgress snapshots = currentState.custom(SnapshotsInProgress.TYPE);
    if (snapshots != null) {
        int changedCount = 0;
        final List<SnapshotsInProgress.Entry> entries = new ArrayList<>();
        for (SnapshotsInProgress.Entry entry : snapshots.entries()) {
            ImmutableOpenMap.Builder<ShardId, ShardSnapshotStatus> shards = ImmutableOpenMap.builder();
            boolean updated = false;

            for (UpdateIndexShardSnapshotStatusRequest updateSnapshotState : tasks) {
                if (entry.snapshot().equals(updateSnapshotState.snapshot())) {
                    logger.trace("[{}] Updating shard [{}] with status [{}]", updateSnapshotState.snapshot(), updateSnapshotState.shardId(), updateSnapshotState.status().state());
                    if (updated == false) {
                        shards.putAll(entry.shards());
                        updated = true;
                    }
                    shards.put(updateSnapshotState.shardId(), updateSnapshotState.status());
                    changedCount++;
                }
            }

            if (updated) {
                if (completed(shards.values()) == false) {
                    entries.add(new SnapshotsInProgress.Entry(entry, shards.build()));
                } else {
                    // Snapshot is finished - mark it as done
                    // TODO: Add PARTIAL_SUCCESS status?
                    SnapshotsInProgress.Entry updatedEntry = new SnapshotsInProgress.Entry(entry, State.SUCCESS, shards.build());
                    entries.add(updatedEntry);
                    // Finalize snapshot in the repository
                    snapshotsService.endSnapshot(updatedEntry);
                    logger.info("snapshot [{}] is done", updatedEntry.snapshot());
                }
            } else {
                entries.add(entry);
            }
        }
        if (changedCount > 0) {
            logger.trace("changed cluster state triggered by {} snapshot state updates", changedCount);

            final SnapshotsInProgress updatedSnapshots = new SnapshotsInProgress(entries.toArray(new SnapshotsInProgress.Entry[entries.size()]));
            return ClusterTasksResult.<UpdateIndexShardSnapshotStatusRequest>builder().successes(tasks).build(
                ClusterState.builder(currentState).putCustom(SnapshotsInProgress.TYPE, updatedSnapshots).build());
        }
    }
    return ClusterTasksResult.<UpdateIndexShardSnapshotStatusRequest>builder().successes(tasks).build(currentState);
}
 
Example 17
Project: MOAAP   File: MatOfKeyPoint.java   View Source Code Vote up 4 votes
public void fromList(List<KeyPoint> lkp) {
    KeyPoint akp[] = lkp.toArray(new KeyPoint[0]);
    fromArray(akp);
}
 
Example 18
Project: DNNLibrary   File: MatOfPoint3f.java   View Source Code Vote up 4 votes
public void fromList(List<Point3> lp) {
    Point3 ap[] = lp.toArray(new Point3[0]);
    fromArray(ap);
}
 
Example 19
Project: incubator-netbeans   File: ClassPathSupport.java   View Source Code Vote up 4 votes
/**
 * 
 * @param classpath
 * @param projectXMLElement
 * @param libraryVolumeType
 * @return
 * @since 1.22
 */
public String[] encodeToStrings( List<Item> classpath, String projectXMLElement, String libraryVolumeType ) {
    List<String> items = new ArrayList<String>();
    for (Item item : classpath) {
        String reference = null;

        switch( item.getType() ) {

            case Item.TYPE_JAR:
                reference = item.getReference();
                if ( item.isBroken() ) {
                    break;
                }
                if (reference == null) {
                    // pass null as expected artifact type to always get file reference
                    reference = referenceHelper.createForeignFileReferenceAsIs(item.getFilePath(), null);
                    if (item.getVariableBasedProperty() != null) {
                        // replace file reference with variable based reference:
                        EditableProperties ep = antProjectHelper.getProperties(AntProjectHelper.PROJECT_PROPERTIES_PATH);
                        ep.setProperty(CommonProjectUtils.getAntPropertyName(reference), item.getVariableBasedProperty());
                        antProjectHelper.putProperties(AntProjectHelper.PROJECT_PROPERTIES_PATH, ep);
                    }
                    item.setReference(reference);
                }
                item.saveSourceAndJavadoc(referenceHelper, updateHelper);
                break;
            case Item.TYPE_LIBRARY:
                reference = item.getReference();
                if ( item.isBroken() ) {
                    break;
                }                    
                Library library = item.getLibrary();                                       
                if (reference == null) {
                    if ( library == null ) {
                        break;
                    }
                    reference = getLibraryReference( item, libraryVolumeType );
                    item.setReference(reference);
                }
                break;    
            case Item.TYPE_ARTIFACT:
                reference = item.getReference();
                if ( item.isBroken() ) {
                    break;
                }
                AntArtifact artifact = item.getArtifact();                                       
                if ( reference == null) {
                    if ( artifact == null ) {
                        break;
                    }
                    reference = referenceHelper.addReference( item.getArtifact(), item.getArtifactURI());
                    item.setReference(reference);
                }
                break;
            case Item.TYPE_CLASSPATH:
                reference = item.getReference();
                break;
        }
        items.add(reference + ":");
    }

    if ( projectXMLElement != null ) {
        callback.storeAdditionalProperties(classpath, projectXMLElement );
    }
    String arr[] = items.toArray(new String[items.size()]);
    // remove ":" from last item:
    if (arr.length != 0) {
        arr[arr.length-1] = arr[arr.length-1].substring(0, arr[arr.length-1].length()-1);
    }
    return arr;
}
 
Example 20
Project: QDrill   File: UnionAll.java   View Source Code Vote up 4 votes
@Override
public PhysicalOperator getNewWithChildren(List<PhysicalOperator> children) {
  return new UnionAll(children.toArray(new PhysicalOperator[children.size()]));
}