Example usage for java.util TreeMap keySet

List of usage examples for java.util TreeMap keySet

Introduction

In this page you can find the example usage for java.util TreeMap keySet.

Prototype

public Set<K> keySet() 

Source Link

Document

Returns a Set view of the keys contained in this map.

Usage

From source file:com.askjeffreyliu.camera2barcode.camera.CameraSource.java

private Size getBestAspectPictureSize(android.util.Size[] supportedPictureSizes) {
    float targetRatio = Utils.getScreenRatio(mContext);
    Size bestSize = null;//from w w  w . j  a  v a2s .  c  om
    TreeMap<Double, List> diffs = new TreeMap<>();

    for (android.util.Size size : supportedPictureSizes) {
        float ratio = (float) size.getWidth() / size.getHeight();
        double diff = Math.abs(ratio - targetRatio);
        if (diff < maxRatioTolerance) {
            if (diffs.keySet().contains(diff)) {
                //add the value to the list
                diffs.get(diff).add(size);
            } else {
                List newList = new ArrayList<>();
                newList.add(size);
                diffs.put(diff, newList);
            }
        }
    }

    //diffs now contains all of the usable sizes
    //now let's see which one has the least amount of
    for (Map.Entry entry : diffs.entrySet()) {
        List<android.util.Size> entries = (List) entry.getValue();
        for (android.util.Size s : entries) {
            if (bestSize == null) {
                bestSize = new Size(s.getWidth(), s.getHeight());
            } else if (bestSize.getWidth() < s.getWidth() || bestSize.getHeight() < s.getHeight()) {
                bestSize = new Size(s.getWidth(), s.getHeight());
            }
        }
    }
    return bestSize;
}

From source file:net.spfbl.core.Analise.java

public static void load() {
    long time = System.currentTimeMillis();
    File file = new File("./data/analise.set");
    if (file.exists()) {
        try {//w  ww  .  j  av a2  s . c om
            TreeSet<Analise> set;
            FileInputStream fileInputStream = new FileInputStream(file);
            try {
                set = SerializationUtils.deserialize(fileInputStream);
            } finally {
                fileInputStream.close();
            }
            for (Analise analise : set) {
                try {
                    if (analise.semaphoreSet == null) {
                        analise.semaphoreSet = new Semaphore(1);
                    }
                    analise.ipSet.addAll(analise.processSet);
                    analise.processSet.clear();
                    add(analise);
                } catch (Exception ex) {
                    Server.logError(ex);
                }
            }
            Server.logLoad(time, file);
        } catch (Exception ex) {
            Server.logError(ex);
        }
    }
    time = System.currentTimeMillis();
    file = new File("./data/cluster.map");
    if (file.exists()) {
        try {
            TreeMap<String, Short[]> map;
            FileInputStream fileInputStream = new FileInputStream(file);
            try {
                map = SerializationUtils.deserialize(fileInputStream);
            } finally {
                fileInputStream.close();
            }
            for (String token : map.keySet()) {
                Short[] value = map.get(token);
                if (token.contains("#") || token.contains(".H.")) {
                    String hostname = token.replace("#", "0");
                    hostname = hostname.replace(".H.", ".0a.");
                    if (Domain.isHostname(hostname)) {
                        clusterMap.put(token, value);
                    }
                } else if (Owner.isOwnerCPF(token.substring(1))) {
                    String ownerID = Owner.normalizeID(token.substring(1));
                    clusterMap.put(ownerID, value);
                } else if (Owner.isOwnerID(token)) {
                    String ownerID = Owner.normalizeID(token);
                    clusterMap.put(ownerID, value);
                } else if (Subnet.isValidCIDR(token)) {
                    clusterMap.put(token, value);
                } else if (Domain.isHostname(token)) {
                    String hostname = Domain.normalizeHostname(token, true);
                    if (Domain.isOfficialTLD(hostname) && !hostname.endsWith(".br")) {
                        clusterMap.put(hostname, value);
                    }
                }
            }
            Server.logLoad(time, file);
        } catch (Exception ex) {
            Server.logError(ex);
        }
    }
}

From source file:org.archive.crawler.admin.StatisticsTracker.java

protected void writeMimetypesReportTo(PrintWriter writer) {
    // header/*from   ww w . ja va2  s  .co m*/
    writer.print("[#urls] [#bytes] [mime-types]\n");
    TreeMap<String, AtomicLong> fd = getReverseSortedCopy(getFileDistribution());
    for (String key : fd.keySet()) {
        // Key is mime type.
        writer.print(Long.toString(fd.get(key).get()));
        writer.print(" ");
        writer.print(Long.toString(getBytesPerFileType(key)));
        writer.print(" ");
        writer.print(key);
        writer.print("\n");
    }
}

From source file:org.squale.squaleweb.applicationlayer.action.export.ppt.AuditReportPPTData.java

/**
 * Create and add the array of results for the application in a slide
 * /* www  . j a v  a  2 s. c  om*/
 * @param slideToSet slide to set
 * @param where place to add results
 * @param factorsMap information about cells
 * @throws IOException if error
 * @throws PPTGeneratorException 
 */
private void createApplicationResultsTable(Slide slideToSet, Rectangle where, TreeMap factorsMap)
        throws IOException, PPTGeneratorException {
    StringBuffer html = new StringBuffer("<html><body><table border='1'>");
    StringBuffer title = new StringBuffer("<tr bgcolor=\"#00FFFF\">");
    List resultsBuffers = new ArrayList();
    // title of first column
    title.append("<td><b>" + WebMessages.getString(request, "component.project") + "</b></td>");
    for (Iterator it = factorsMap.keySet().iterator(); it.hasNext();) {
        String factorName = (String) it.next();
        // factor title
        title.append("<td><b>" + factorName + "</b></td>");
        Map results = (TreeMap) factorsMap.get(factorName);
        int rowProj = 1;
        for (Iterator projIt = results.keySet().iterator(); projIt.hasNext(); rowProj++) {
            String projName = (String) projIt.next();
            StringBuffer projectResults = null;
            if (rowProj > resultsBuffers.size()) {
                projectResults = new StringBuffer("<td>" + projName + "</td>");
                resultsBuffers.add(projectResults);
            } else {
                projectResults = (StringBuffer) resultsBuffers.get(rowProj - 1);
            }
            // project title
            // fill factor column
            appendFactorResultToProjectRow(projectResults, (Float[]) results.get(projName));
            projectResults.append("</td>");
        }
    }
    html.append(title + "</tr>");
    for (int i = 0; i < resultsBuffers.size(); i++) {
        html.append("<tr>");
        html.append((StringBuffer) resultsBuffers.get(i));
        html.append("</tr>");
    }
    html.append("</table></body></html>");
    addHtmlPicture(slideToSet, html.toString(), where.x, where.y);
}

From source file:org.archive.crawler.admin.StatisticsTracker.java

protected void writeResponseCodeReportTo(PrintWriter writer) {
    // Build header.
    writer.print("[rescode] [#urls]\n");
    TreeMap<String, AtomicLong> scd = getReverseSortedCopy(getStatusCodeDistribution());
    for (String key : scd.keySet()) {
        writer.print(key);// ww  w .  j  av  a 2  s.  co m
        writer.print(" ");
        writer.print(Long.toString(scd.get(key).get()));
        writer.print("\n");
    }
}

From source file:org.openmicroscopy.shoola.agents.measurement.view.IntensityResultsView.java

/**
 * Adds the statistics from the ROIShapes of the select ROI to the table.
 *//*from ww w  . j a  va2  s .  c  o  m*/
private void addAllResults() {
    Set<Figure> selectedFigures = view.getDrawingView().getSelectedFigures();
    if (CollectionUtils.isEmpty(selectedFigures) || state == State.ANALYSING)
        return;
    state = State.ANALYSING;
    setControls(false);
    List<ROIShape> shapeList = new ArrayList<ROIShape>();
    final Set<ROIShape> alreadyInTable = getShapesInRows();

    Iterator<Figure> i = selectedFigures.iterator();
    ROIFigure fig;
    TreeMap<Coord3D, ROIShape> treeMap;
    Iterator<Coord3D> j;
    ROIShape shape;
    Map<ROIShape, Map<Integer, ROIShapeStats>> analysisResults = model.getAnalysisResults();
    if (analysisResults == null)
        analysisResults = Collections.emptyMap();
    while (i.hasNext()) {
        fig = (ROIFigure) i.next();
        if (!(fig instanceof MeasureTextFigure)) {
            treeMap = fig.getROI().getShapes();
            j = treeMap.keySet().iterator();
            while (j.hasNext()) {
                shape = treeMap.get(j.next());
                if (!alreadyInTable.contains(shape)) {
                    final Map<Integer, ROIShapeStats> shapeStatsByChannel = analysisResults.get(shape);
                    if (shapeStatsByChannel == null || shapeStatsByChannel.isEmpty())
                        /* if empty, they were probably wiped out by AnalysisStatsWrapper.convertStats */
                        shapeList.add(shape);
                }
            }
        }
    }
    if (shapeList.isEmpty()) {
        if (!analysisResults.isEmpty()) {
            displayAnalysisResults();
        }
    } else {
        view.calculateStats(shapeList);
    }
}

From source file:org.openlaszlo.sc.SWF9External.java

private String optionsToString() {
    StringBuffer result = new StringBuffer();
    result.append("{");
    TreeMap sorted = new TreeMap(options);
    for (Iterator i = sorted.keySet().iterator(); i.hasNext();) {
        Object key = i.next();//from   w w w . ja  v  a  2s  .  c om
        result.append(key);
        result.append(": ");
        result.append(sorted.get(key));
        if (i.hasNext()) {
            result.append(", ");
        }
    }
    result.append("}");
    return result.toString();
}

From source file:org.opentaps.domain.container.ConstantsGeneratorContainer.java

private TreeMap<String, ConstantModel> readConstantConfiguration(Properties config) throws ContainerException {
    TreeMap<String, ConstantModel> models = new TreeMap<String, ConstantModel>();
    // first collect the entity names
    Enumeration<?> propertyNames = config.propertyNames();
    while (propertyNames.hasMoreElements()) {
        String key = (String) propertyNames.nextElement();
        if (GENERATE_VALUE.equals(config.getProperty(key))) {
            if (models.containsKey(key)) {
                throw new ContainerException("Entity: [" + key + "] already defined in the configuration.");
            }//from   ww w.jav  a2 s.  co m

            models.put(key, new ConstantModel(key));
        }
    }
    // then for each entity read the configuration
    for (String key : models.keySet()) {
        ConstantModel model = models.get(key);
        model.setClassName(config.getProperty(key + ".className"));
        model.setDescription(config.getProperty(key + ".description"));
        model.setTypeField(config.getProperty(key + ".typeField"));
        model.setNameField(config.getProperty(key + ".nameField"));
        model.setDescriptionField(config.getProperty(key + ".descriptionField"));
        model.setConstantField(config.getProperty(key + ".constantField"));
        model.setWhere(config.getProperty(key + ".where"));
    }

    return models;
}

From source file:org.kalypso.project.database.server.ProjectDatabase.java

@Override
public KalypsoProjectBean[] getProjectHeads(final String projectType) {
    synchronized (this) {
        /** Getting the Session Factory and session */
        final Session session = FACTORY.getCurrentSession();

        /** Starting the Transaction */
        final Transaction tx = session.beginTransaction();

        /* names of existing projects */
        final List<?> names = session.createQuery(String.format(
                "select m_unixName from KalypsoProjectBean where m_projectType = '%s' ORDER by m_name", //$NON-NLS-1$
                projectType)).list();// w  w  w. j a v a 2s  . c  om
        tx.commit();

        final Set<String> projects = new HashSet<>();

        for (final Object object : names) {
            if (!(object instanceof String))
                continue;

            final String name = object.toString();
            projects.add(name);
        }

        final List<KalypsoProjectBean> projectBeans = new ArrayList<>();

        for (final String project : projects) {
            final TreeMap<Integer, KalypsoProjectBean> myBeans = new TreeMap<>();

            final Session mySession = FACTORY.getCurrentSession();
            final Transaction myTx = mySession.beginTransaction();
            final List<?> beans = mySession.createQuery(String.format(
                    "from KalypsoProjectBean where m_unixName = '%s'  ORDER by m_projectVersion", project)) //$NON-NLS-1$
                    .list();
            myTx.commit();

            for (final Object object : beans) {
                if (!(object instanceof KalypsoProjectBean))
                    continue;

                final KalypsoProjectBean b = (KalypsoProjectBean) object;
                myBeans.put(b.getProjectVersion(), b);
            }

            final Integer[] keys = myBeans.keySet().toArray(new Integer[] {});

            /* determine head */
            final KalypsoProjectBean head = myBeans.get(keys[keys.length - 1]);

            KalypsoProjectBean[] values = myBeans.values().toArray(new KalypsoProjectBean[] {});
            values = ArrayUtils.remove(values, values.length - 1); // remove last entry -> cycle!

            // TODO check needed? - order by clauses
            Arrays.sort(values, new Comparator<KalypsoProjectBean>() {
                @Override
                public int compare(final KalypsoProjectBean o1, final KalypsoProjectBean o2) {
                    return o1.getProjectVersion().compareTo(o2.getProjectVersion());
                }
            });

            head.setChildren(values);
            projectBeans.add(head);
        }

        return projectBeans.toArray(new KalypsoProjectBean[] {});
    }

}

From source file:IndexService.Indexer.java

private List<IRecord> getRecord(TreeMap<String, TreeSet<Integer>> indexresult,
        HashMap<String, Boolean> iscolumn, String indexids, int limit, int fieldnum) throws IOException {
    long time = System.currentTimeMillis();
    List<IRecord> result = new ArrayList<IRecord>();
    boolean returnallfields = false;
    String[] idxids;//from ww  w. ja va2s .co m
    ArrayList<Integer> idxs = new ArrayList<Integer>();
    if (indexids == null) {
        returnallfields = true;
        idxids = new String[0];
    } else {
        idxids = indexids.split(",");
        for (int i = 0; i < idxids.length; i++) {
            idxs.add(Integer.parseInt(idxids[i].trim()));
        }
    }
    int i = 0;
    label: for (String file : indexresult.keySet()) {
        if (!iscolumn.get(file)) {
            IFormatDataFile ifdf = new IFormatDataFile(conf);
            if (returnallfields)
                ifdf.open(file);
            else
                ifdf.open(file, idxs);
            for (Integer line : indexresult.get(file)) {
                if (limit >= 0 && i >= limit) {
                    ifdf.close();
                    break label;
                }
                IRecord rec = ifdf.getByLine(line);
                result.add(rec);
                i++;
            }
            ifdf.close();
        } else {
            IColumnDataFile icdf = new IColumnDataFile(conf);
            if (returnallfields)
                icdf.open(file);
            else
                icdf.open(file, idxs);
            for (Integer line : indexresult.get(file)) {
                if (limit >= 0 && i >= limit) {
                    icdf.close();
                    break label;
                }
                IRecord rec = icdf.getByLine(line);
                result.add(rec);
                i++;
            }
            icdf.close();
        }
    }
    System.out.println("getRecord time:\t" + (System.currentTimeMillis() - time) / 1000 + "s");
    return result;
}