Example usage for java.util TreeSet toArray

List of usage examples for java.util TreeSet toArray

Introduction

In this page you can find the example usage for java.util TreeSet toArray.

Prototype

Object[] toArray();

Source Link

Document

Returns an array containing all of the elements in this set.

Usage

From source file:Main.java

public static void main(String[] args) {
    TreeSet<Integer> tSet = new TreeSet<Integer>();
    tSet.add(new Integer("1"));
    tSet.add(new Integer("2"));
    tSet.add(new Integer("3"));

    Object[] objArray = tSet.toArray();
    for (Object obj : objArray) {
        System.out.println(obj);/*from ww  w.j  a  va2s. c om*/
    }
}

From source file:it.unibz.instasearch.prefs.PreferenceInitializer.java

/**
 * Get extensions that Eclipse knows of and the default ones
 * @return comma separated string of extensions
 *//* w  w w  . ja  v  a2s .co  m*/
public static String getIndexableExtensions() {
    String defaultExtArray[] = DEFAULT_EXTENSIONS.split(",");

    TreeSet<String> extensions = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
    extensions.addAll(Arrays.asList(defaultExtArray));

    IFileEditorMapping[] allMappings = ((EditorRegistry) PlatformUI.getWorkbench().getEditorRegistry())
            .getUnifiedMappings();

    IContentType text = Platform.getContentTypeManager().getContentType(IContentTypeManager.CT_TEXT);

    for (int i = 0; i < allMappings.length; i++) {
        if (allMappings[i].getName().equals("*")) {
            String ext = allMappings[i].getExtension();
            IContentType type = Platform.getContentTypeManager().findContentTypeFor("." + ext);

            if (type != null && type.isKindOf(text))
                extensions.add(ext);
        }
    }

    IContentType[] types = Platform.getContentTypeManager().getAllContentTypes();
    for (IContentType type : types) {
        if (type.isKindOf(text)) {
            String exts[] = type.getFileSpecs(IContentType.FILE_EXTENSION_SPEC);
            extensions.addAll(Arrays.asList(exts));
        }
    }

    return StringUtils.join(extensions.toArray(), ",");
}

From source file:com.mawujun.util.ObjectUtils.java

/**
 * Find the "best guess" middle value among comparables. If there is an even
 * number of total values, the lower of the two middle values will be returned.
 * @param <T> type of values processed by this method
 * @param items to compare//from ww w  .j  a va2s . c  o m
 * @return T at middle position
 * @throws NullPointerException if items is {@code null}
 * @throws IllegalArgumentException if items is empty or contains {@code null} values
 * @since 3.0.1
 */
public static <T extends Comparable<? super T>> T median(T... items) {
    Validate.notEmpty(items);
    Validate.noNullElements(items);
    TreeSet<T> sort = new TreeSet<T>();
    Collections.addAll(sort, items);
    @SuppressWarnings("unchecked") //we know all items added were T instances
    T result = (T) sort.toArray()[(sort.size() - 1) / 2];
    return result;
}

From source file:com.mawujun.util.ObjectUtils.java

/**
 * Find the "best guess" middle value among comparables. If there is an even
 * number of total values, the lower of the two middle values will be returned.
 * @param <T> type of values processed by this method
 * @param comparator to use for comparisons
 * @param items to compare//from  w w w .  j  a v  a 2  s. c  o m
 * @return T at middle position
 * @throws NullPointerException if items or comparator is {@code null}
 * @throws IllegalArgumentException if items is empty or contains {@code null} values
 * @since 3.0.1
 */
public static <T> T median(Comparator<T> comparator, T... items) {
    Validate.notEmpty(items, "null/empty items");
    Validate.noNullElements(items);
    Validate.notNull(comparator, "null comparator");
    TreeSet<T> sort = new TreeSet<T>(comparator);
    Collections.addAll(sort, items);
    @SuppressWarnings("unchecked") //we know all items added were T instances
    T result = (T) sort.toArray()[(sort.size() - 1) / 2];
    return result;
}

From source file:com.safi.workshop.sqlexplorer.sqleditor.ExtendedCompletionProposal.java

/**
 * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#computeCompletionProposals(org.eclipse.jface.text.ITextViewer,
 *      int)/* w  w w.j  av  a  2  s .c  om*/
 */
public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int documentOffset) {
    if (dictionary == null)
        return null;
    String text = viewer.getDocument().get();
    String string = text.substring(0, documentOffset);

    if (string.equals("")) //$NON-NLS-1$
        return null;
    int position = string.length() - 1;
    char character;

    while (position > 0) {
        character = string.charAt(position);
        if (!Character.isJavaIdentifierPart(character) && (character != '.'))
            break;
        --position;
    }
    if (position == 0)
        position = -1;
    string = string.substring(position + 1);
    // JFaceDbcPlugin.error("String: "+string,new Exception());
    if (StringUtils.isBlank(string)) {
        List<ICompletionProposal> proposals = new ArrayList<ICompletionProposal>();
        String[] names = dictionary.getAllCatalogSchemas();
        ICompletionProposal[] tempProps = new ICompletionProposal[names.length];
        for (int i = 0; i < names.length; i++) {
            tempProps[i] = new CompletionProposal(names[i], documentOffset, 0, names[i].length(), catalogImage,
                    names[i], null, null);
        }
        proposals.addAll(Arrays.asList(tempProps));

        names = dictionary.getAllTables();

        tempProps = new ICompletionProposal[names.length];
        for (int i = 0; i < names.length; i++) {
            tempProps[i] = new CompletionProposal(names[i], documentOffset, 0, names[i].length(), tableImage,
                    names[i], null, null);
        }
        proposals.addAll(Arrays.asList(tempProps));

        names = dictionary.getAllExternalObjects();
        tempProps = new ICompletionProposal[names.length];
        for (int i = 0; i < names.length; i++) {
            tempProps[i] = new CompletionProposal(names[i], documentOffset, 0, names[i].length(), keywordImage,
                    names[i], null, null);
        }
        proposals.addAll(Arrays.asList(tempProps));

        return proposals.toArray(new ICompletionProposal[proposals.size()]);
    }
    // if (string == null || string.equals(""))
    // return null;

    string = string.toLowerCase();

    int length = string.length();
    // if (length < 1)
    // return null;
    int dotIndex = string.lastIndexOf("."); //$NON-NLS-1$
    if (string.charAt(length - 1) == ' ') {
        return null;
    } else if (string.charAt(length - 1) == '.') {// Last typed character
        // is '.'
        String name = string.substring(0, length - 1);
        if (name == null)
            return null;
        int otherDot = name.lastIndexOf(".");
        if (otherDot != -1)
            name = name.substring(otherDot + 1);
        if (name == null || name.equals(""))
            return null;

        TreeSet st = (TreeSet) dictionary.getColumnListByTableName(name);
        if (st != null) {
            ArrayList list = (ArrayList) dictionary.getByTableName(name);
            if (list == null)
                return null;
            TableNode nd = null;
            if (list.size() >= 1)
                nd = (TableNode) list.get(0);
            else
                return null;
            Object[] obj = st.toArray();
            String[] arr = new String[obj.length];
            System.arraycopy(obj, 0, arr, 0, obj.length);

            ICompletionProposal[] result = new ICompletionProposal[arr.length];
            String tableDesc = null;
            if (nd != null)
                tableDesc = nd.getTableDesc();
            for (int i = 0; i < arr.length; i++) {
                result[i] = new CompletionProposal(arr[i], documentOffset, 0, arr[i].length(), colImage, arr[i],
                        null, tableDesc);
            }
            return result;
        }
        INode node = (INode) dictionary.getByCatalogSchemaName(name);
        if (node != null) {
            Object children[] = node.getChildNodes();
            ArrayList propList = new ArrayList();
            if (children != null) {
                for (Object element : children) {
                    String childName = element.toString().toLowerCase();
                    if (childName.equals("table") || childName.equals("view") || childName.equals("tables")) {
                        Object[] tables = ((INode) element).getChildNodes();
                        if (tables != null) {
                            for (Object table : tables) {
                                Image tmpImage = null;
                                String tableName = table.toString();
                                if (table instanceof TableNode) {
                                    if (((TableNode) table).isTable())
                                        tmpImage = tableImage;
                                    else if (((TableNode) table).isView())
                                        tmpImage = viewImage;
                                    propList.add(new ExtendedCompletionProposal(tableName, documentOffset, 0,
                                            tableName.length(), tmpImage, tableName, (TableNode) table));
                                }

                            }
                        }
                    }
                }
            }
            ICompletionProposal[] res = new ICompletionProposal[propList.size()];
            System.arraycopy(propList.toArray(), 0, res, 0, propList.size());
            Arrays.sort(res, new ICompletionProposalComparator());
            return res;
        }
    } else if (dotIndex == -1)// The string does not contain "."
    {
        String[] keywordProposal = Dictionary.matchKeywordsPrefix(string);
        ICompletionProposal[] resKey = new ICompletionProposal[keywordProposal.length];
        for (int i = 0; i < keywordProposal.length; i++) {
            resKey[i] = new CompletionProposal(keywordProposal[i], documentOffset - length, length,
                    keywordProposal[i].length(), keywordImage, keywordProposal[i], null, null);
        }

        String[] proposalsString = dictionary.matchTablePrefix(string.toLowerCase());

        ArrayList propList = new ArrayList();
        for (String element : proposalsString) {
            ArrayList ls = dictionary.getTableObjectList(element);
            for (int j = 0; j < ls.size(); j++) {

                TableNode tbNode = (TableNode) ls.get(j);
                Image tmpImage = null;
                if (tbNode.isView())
                    tmpImage = viewImage;
                else if (tbNode.isTable())
                    tmpImage = tableImage;

                ICompletionProposal cmp = new ExtendedCompletionProposal(element, documentOffset - length,
                        length, element.length(), tmpImage, element, tbNode);
                propList.add(cmp);

            }
        }
        String[] proposalsString2 = dictionary.matchCatalogSchemaPrefix(string.toLowerCase());
        ICompletionProposal[] resKey2 = new ICompletionProposal[proposalsString2.length];
        for (int i = 0; i < proposalsString2.length; i++) {
            resKey2[i] = new CompletionProposal(proposalsString2[i], documentOffset - length, length,
                    proposalsString2[i].length(), catalogImage, proposalsString2[i], null, null);
        }

        ICompletionProposal[] res = new ICompletionProposal[propList.size() + keywordProposal.length
                + resKey2.length];
        System.arraycopy(resKey, 0, res, 0, resKey.length);
        System.arraycopy(propList.toArray(), 0, res, resKey.length, propList.size());
        System.arraycopy(resKey2, 0, res, resKey.length + propList.size(), resKey2.length);
        Arrays.sort(res, new ICompletionProposalComparator());
        return res;
    } else if (dotIndex != -1) {
        String firstPart = string.substring(0, dotIndex);
        int otherDot = firstPart.indexOf(".");
        if (otherDot != -1)
            firstPart = firstPart.substring(otherDot + 1);
        String lastPart = string.substring(dotIndex + 1);
        if (lastPart == null || firstPart == null || lastPart.equals("") || firstPart.equals(""))
            return null;
        TreeSet st = (TreeSet) dictionary.getColumnListByTableName(firstPart);
        if (st != null) {
            Iterator iter = st.iterator();
            ArrayList propList = new ArrayList();
            while (iter.hasNext()) {
                String colName = (String) iter.next();
                int length2 = lastPart.length();
                if (colName.length() >= length2) {
                    if ((colName.substring(0, lastPart.length())).equalsIgnoreCase(lastPart)) {
                        CompletionProposal cmp = new CompletionProposal(colName, documentOffset - length2,
                                length2, colName.length(), colImage, colName, null, null);
                        propList.add(cmp);
                    }
                }
            }
            ICompletionProposal[] res = new ICompletionProposal[propList.size()];
            System.arraycopy(propList.toArray(), 0, res, 0, propList.size());
            return res;
        }
        INode node = (INode) dictionary.getByCatalogSchemaName(firstPart);
        if (node != null) {
            String[] proposalsString = dictionary.matchTablePrefix(lastPart.toLowerCase());
            ArrayList propList = new ArrayList();
            for (String element : proposalsString) {
                ArrayList ls = dictionary.getTableObjectList(element);
                for (int j = 0; j < ls.size(); j++) {
                    TableNode tbNode = (TableNode) ls.get(j);
                    Image tmpImage = null;
                    TableFolderNode totn = (TableFolderNode) tbNode.getParent();

                    INode catSchema = totn.getParent();
                    if (catSchema == node) {
                        if (tbNode.isView())
                            tmpImage = viewImage;
                        else if (tbNode.isTable())
                            tmpImage = tableImage;
                        ICompletionProposal cmp = new ExtendedCompletionProposal(element,
                                documentOffset - lastPart.length(), lastPart.length(), element.length(),
                                tmpImage, element, tbNode);
                        propList.add(cmp);
                    }
                }
            }
            ICompletionProposal[] res = new ICompletionProposal[propList.size()];
            System.arraycopy(propList.toArray(), 0, res, 0, propList.size());
            return res;
        }
    }
    return null;

}

From source file:org.esa.snap.smart.configurator.ui.PerformancePanel.java

private Object[] getBenchmarkOperators() {
    GPF gpf = GPF.getDefaultInstance();/*from w  w w  .  ja v a 2 s  .c o m*/
    if (gpf.getOperatorSpiRegistry().getOperatorSpis().isEmpty()) {
        gpf.getOperatorSpiRegistry().loadOperatorSpis();
    }
    ServiceRegistry<BenchmarkOperatorProvider> benchemarkOperatorServiceRegistry = ServiceRegistryManager
            .getInstance().getServiceRegistry(BenchmarkOperatorProvider.class);
    SnapCoreActivator.loadServices(benchemarkOperatorServiceRegistry);
    Set<BenchmarkOperatorProvider> providers = benchemarkOperatorServiceRegistry.getServices();

    TreeSet<String> externalOperatorsAliases = new TreeSet<>();
    for (BenchmarkOperatorProvider provider : providers) {
        Set<OperatorSpi> operatorSpis = provider.getBenchmarkOperators();
        for (OperatorSpi operatorSpi : operatorSpis) {
            externalOperatorsAliases.add(operatorSpi.getOperatorAlias());
        }
    }

    return externalOperatorsAliases.toArray();
}

From source file:com.ephesoft.dcma.tabbed.TabbedPdfExporter.java

/**
 * This will create the document map on the basis of order and load the error pdf if the document is not present.
 * //from www. jav  a  2  s  . co m
 * @param parsedXMLFile {@link Batch}
 * @param batchInstanceID{@link String}
 * @param propertyFile{@link String}
 * @return documentPDFMap {@link LinkedHashMap<String, List<String>>}
 * @throws Exception
 */
private LinkedHashMap<String, List<String>> createBatchClassDocumentPDFMap(final Batch parsedXMLFile,
        String batchInstanceID, String propertyFile) throws Exception {
    String errorPDFPath = batchSchemaService.getAbsolutePath(parsedXMLFile.getBatchClassIdentifier(),
            batchSchemaService.getScriptConfigFolderName(), true);
    List<String> batchDocumentTypeNameList = new ArrayList<String>();
    String batchClassId = parsedXMLFile.getBatchClassIdentifier();
    BatchClass batchClass = batchClassService.getBatchClassByIdentifierIncludingDeleted(batchClassId);
    List<DocumentType> batchDocumentList = batchClass.getDocumentTypes();
    for (DocumentType docType : batchDocumentList) {
        if (!docType.isHidden()) {
            batchDocumentTypeNameList.add(docType.getName());
        }
    }
    List<String> sortedDocumentList = new ArrayList<String>();
    Map<String, Integer> propMap = fetchDocNameMapping(propertyFile);
    List<String> mapKeys = new ArrayList<String>(propMap.keySet());
    List<Integer> mapValues = new ArrayList<Integer>(propMap.values());
    TreeSet<Integer> sortedSet = new TreeSet<Integer>(mapValues);
    if (sortedSet.size() != propMap.size()) {
        LOGGER.error("Same priority is defined for more than one document type. Invalid scenario.");
        throw new DCMAApplicationException("Property file for documents not valid");
    } else {
        Object[] sortedArray = sortedSet.toArray();
        int size = sortedArray.length;
        for (int i = 0; i < size; i++) {
            String documentType = (String) mapKeys.get(mapValues.indexOf(sortedArray[i]));
            for (int documentIndex = 0; documentIndex < batchDocumentTypeNameList.size(); documentIndex++) {
                if (documentType.equals(batchDocumentTypeNameList.get(documentIndex))) {
                    sortedDocumentList.add(batchDocumentTypeNameList.get(documentIndex));
                }
            }
        }
        List<Document> xmlDocuments = parsedXMLFile.getDocuments().getDocument();
        // check if any document in batch xml is not present in export props then send the batch to error.
        checkIfAnyXmlDocIsNotInProps(sortedDocumentList, xmlDocuments);
        LinkedHashMap<String, List<String>> documentPDFMap = new LinkedHashMap<String, List<String>>();
        int startPageNumber = 1;
        int docIdentifier = 1;
        int batchDocumentIndex = 0;
        for (String document : sortedDocumentList) {
            List<String> detailsList = new LinkedList<String>();
            String documentId = TabbedPdfConstant.DOCUMENT_IDENTIFIER + docIdentifier;
            int numberOfPages;
            String documentType;
            String pdfFile = null;

            if (batchDocumentIndex + 1 <= xmlDocuments.size()) {
                Document xmlDocument = xmlDocuments.get(batchDocumentIndex);
                if (document.equals(xmlDocument.getType())) {
                    List<Page> listOfPages = xmlDocuments.get(batchDocumentIndex).getPages().getPage();
                    LOGGER.info("Document documentid =" + documentId + " contains the following info:");
                    numberOfPages = listOfPages.size();
                    documentType = xmlDocument.getType();
                    pdfFile = xmlDocument.getMultiPagePdfFile();
                    detailsList.add(documentType);
                    detailsList.add(String.valueOf(startPageNumber));
                    if (pdfFile != null && !pdfFile.isEmpty()) {
                        File fPDFFile = batchSchemaService.getFile(batchInstanceID, pdfFile);
                        if (fPDFFile.exists()) {
                            LOGGER.info("PDF File Name:" + fPDFFile);
                            detailsList.add(fPDFFile.getAbsolutePath());

                        } else {
                            throw new DCMAApplicationException("File does not exist. File Name=" + fPDFFile);
                        }

                        docIdentifier++;
                        startPageNumber = startPageNumber + numberOfPages;
                        documentPDFMap.put(documentId, detailsList);
                    } else {
                        throw new DCMAApplicationException("MultiPagePDF file does not exist in batch xml.");
                    }
                    batchDocumentIndex++;
                } else {
                    startPageNumber = appendPlaceholder(errorPDFPath, xmlDocuments, documentPDFMap,
                            startPageNumber, docIdentifier, document, detailsList, documentId);
                    docIdentifier++;
                }
            } else {
                startPageNumber = appendPlaceholder(errorPDFPath, xmlDocuments, documentPDFMap, startPageNumber,
                        docIdentifier, document, detailsList, documentId);
                docIdentifier++;
            }
        }
        return documentPDFMap;
    }
}

From source file:dhbw.ka.mwi.businesshorizon2.ui.process.period.timeline.TimelinePresenter.java

/**
 * Methode wird aus der View aufgerufen um die letzte vergangene Periode zu
 * entfernen/*ww  w  .ja v  a  2  s.co  m*/
 * 
 * @param period
 *            Periode die entfernt werden soll
 */
public void removeLastPastPeriod(Period periodInterface) {
    getView().removePastPeriod();
    pastPeriods.removePeriod(periodInterface);
    sumPastPeriods--;
    logger.debug("Fixed Periods: " + fixedPastPeriods + " Sum Periods: " + sumPastPeriods);

    // Anzahl der Perioden wird im Projekt angepasst
    projectProxy.getSelectedProject()
            .setRelevantPastPeriods(projectProxy.getSelectedProject().getSpecifiedPastPeriods() - 1);

    projectProxy.getSelectedProject().setDeterministicPeriods(futurePeriods);

    periodenanzahl_geaendert();

    // andere Periode anzeigen
    // TODO
    try {
        TreeSet set = projectProxy.getSelectedProject().getStochasticPeriods().getPeriods();
        int laenge = set.toArray().length;
        periodClicked((Period) set.toArray()[0]);
    } catch (Exception e) {
    }
}

From source file:dhbw.ka.mwi.businesshorizon2.ui.process.period.timeline.TimelinePresenter.java

/**
 * Methode zum Aufruf aus der View. Ruft die Folgemethode auf.
 *//*  w ww.  j  a va  2s. com*/
public void addPastPeriod() {
    // Anzahl der Perioden wird im Projekt angepasst
    // muss passieren, bevor das Event gefeuert wird
    projectProxy.getSelectedProject()
            .setRelevantPastPeriods(projectProxy.getSelectedProject().getSpecifiedPastPeriods() + 1);
    projectProxy.getSelectedProject().setStochasticPeriods(pastPeriods);

    addPastPeriods(1, projectProxy.getSelectedProject().getProjectInputType().getStochasticInput());

    eventBus.fireEvent(new ShowPeriodViewEvent());

    // andere Periode anzeigen
    // TODO
    try {
        TreeSet set = projectProxy.getSelectedProject().getStochasticPeriods().getPeriods();
        int laenge = set.toArray().length;
        Period t;
        t = (Period) set.toArray()[0];
        periodClicked(t);
    } catch (Exception e) {
        logger.debug("Fehler beim anzeigen der neuesten Periode");
    }

}

From source file:dhbw.ka.mwi.businesshorizon2.ui.process.period.timeline.TimelinePresenter.java

/**
 * Methode wird aus der View aufgerufen um die letzte zukuenftige Periode zu
 * entfernen//from   www  .j a v  a 2 s  . c  o  m
 * 
 * @param period
 *            Periode die entfernt werden soll
 */
public void removeLastFuturePeriod(Period period) {
    getView().removeFuturePeriod();
    futurePeriods.removePeriod(period);
    sumFuturePeriods--;

    // Anzahl der Perioden wird im Projekt angepasst

    projectProxy.getSelectedProject().setPeriodsToForecast_deterministic(
            projectProxy.getSelectedProject().getPeriodsToForecast_deterministic() - 1);

    projectProxy.getSelectedProject().setDeterministicPeriods(futurePeriods);
    periodenanzahl_geaendert();

    // andere Periode anzeigen
    try {
        TreeSet set = projectProxy.getSelectedProject().getDeterministicPeriods().getPeriods();
        int laenge = set.toArray().length;
        periodClicked((Period) set.toArray()[laenge - 1]);
    } catch (Exception e) {
    }
}