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.sec.ose.osi.report.standard.data.BillOfMaterialsRowGenerator.java

private String getFileCountForFolders(ArrayList<IdentifiedFilesRow> fileEntList) {

    TreeMap<String, Integer> map = new TreeMap<String, Integer>(); // parent path, value

    if (fileEntList == null || fileEntList.size() == 0)
        return "<None>";

    for (IdentifiedFilesRow ent : fileEntList) {
        String parentPath = (new File(ent.getFullPath())).getParent();
        if (parentPath == null)
            parentPath = "";

        if (map.containsKey(parentPath) == false) {
            map.put(parentPath, 0);//from   w  w w. j  a  v a2s .com
        }

        map.put(parentPath, map.get(parentPath) + 1);
    }

    if (map.size() == 0)
        return "";
    if (map.size() == 1)
        return ("(" + map.get(map.firstKey()) + " files)\n");

    String msg = "";
    for (String path : map.keySet()) {
        msg += path;
        if (!path.endsWith("/"))
            msg += "/ ";
        msg += "(" + map.get(path) + " files)\n";
    }
    msg = msg.replace("\\", "/");

    if (msg.length() > 0) {
        return msg.substring(0, msg.length() - 1);
    }

    return "";
}

From source file:it.polito.tellmefirst.web.rest.clients.ClientEpub.java

public ArrayList<ClassifyOutput> sortByRank(HashMap<ClassifyOutput, Integer> inputList) {

    LOG.debug("[sortByRank] - BEGIN");

    ArrayList<ClassifyOutput> result = new ArrayList<>();
    LinkedMap apacheMap = new LinkedMap(inputList);
    for (int i = 0; i < apacheMap.size() - 1; i++) {
        TreeMap<Float, ClassifyOutput> treeMap = new TreeMap<>(Collections.reverseOrder());
        do {/*from  w w w  .  jav  a2 s  .  c  om*/
            i++;
            treeMap.put(Float.valueOf(((ClassifyOutput) apacheMap.get(i - 1)).getScore()),
                    (ClassifyOutput) apacheMap.get(i - 1));
        } while (i < apacheMap.size() && apacheMap.getValue(i) == apacheMap.getValue(i - 1));
        i--;
        for (Float score : treeMap.keySet()) {
            result.add(treeMap.get(score));
        }
    }

    LOG.debug("[sortByRank] - END");
    return result;
}

From source file:agendavital.modelo.data.Noticia.java

public static TreeMap<LocalDate, ArrayList<Noticia>> buscar(String _parametro)
        throws ConexionBDIncorrecta, SQLException {
    final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
    ArrayList<String> _tags = UtilidadesBusqueda.separarPalabras(_parametro);
    TreeMap<LocalDate, ArrayList<Noticia>> busqueda = null;
    try (Connection conexion = ConfigBD.conectar()) {
        busqueda = new TreeMap<>();
        for (String _tag : _tags) {
            String tag = ConfigBD.String2Sql(_tag, true);
            String buscar = String.format("SELECT id_Noticia, fecha from noticias "
                    + "WHERE id_noticia IN (SELECT id_noticia from momentos_noticias_etiquetas "
                    + "WHERE id_etiqueta IN (SELECT id_etiqueta from etiquetas WHERE nombre LIKE %s)) "
                    + "OR titulo LIKE %s " + "OR cuerpo LIKE %s " + "OR categoria LIKE %s "
                    + "OR fecha LIKE %s; ", tag, tag, tag, tag, tag);
            ResultSet rs = conexion.createStatement().executeQuery(buscar);
            while (rs.next()) {
                LocalDate date = LocalDate.parse(rs.getString("fecha"), dateFormatter);
                Noticia insertarNoticia = new Noticia(rs.getInt("id_noticia"));
                if (busqueda.containsKey(date)) {
                    boolean encontrado = false;
                    for (int i = 0; i < busqueda.get(date).size() && !encontrado; i++)
                        if (busqueda.get(date).get(i).getId() == insertarNoticia.getId())
                            encontrado = true;
                    if (!encontrado)
                        busqueda.get(date).add(insertarNoticia);
                } else {
                    busqueda.put(date, new ArrayList<>());
                    busqueda.get(date).add(insertarNoticia);
                }//from w ww.j a v  a  2  s  . c o  m
            }

        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    Iterator it = busqueda.keySet().iterator();
    return busqueda;
}

From source file:io.mapzone.arena.analytics.graph.SingleSourceNodeGraphFunction.java

@Override
public void createContents(final MdToolkit tk, final Composite parent, final Graph graph) {
    try {/*w w w  . jav a  2s  .c  o  m*/
        super.createContents(tk, parent, graph);
        final FeaturePropertySelectorUI sourcePropertiesUI = new FeaturePropertySelectorUI(tk, parent, prop -> {
            this.selectedSourcePropertyDescriptor = prop;
            EventManager.instance().publish(new GraphFunctionConfigurationChangedEvent(
                    SingleSourceNodeGraphFunction.this, "sourcePropertyDescriptor", prop));
        });
        final FeatureSourceSelectorUI sourceFeaturesUI = new FeatureSourceSelectorUI(tk, parent, fs -> {
            this.selectedSourceFeatureSource = fs;
            EventManager.instance().publish(new GraphFunctionConfigurationChangedEvent(
                    SingleSourceNodeGraphFunction.this, "sourceFeatureSource", fs));
            sourcePropertiesUI.setFeatureSource(fs);
        });

        final TreeMap<String, EdgeFunction> edgeFunctions = Maps.newTreeMap();
        for (Class<EdgeFunction> cl : availableFunctions) {
            try {
                EdgeFunction function = cl.newInstance();
                function.init(this);
                edgeFunctions.put(function.title(), function);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        final Composite edgeFunctionContainer = tk.createComposite(parent, SWT.NONE);
        edgeFunctionContainer.setLayout(FormLayoutFactory.defaults().create());

        final ComboViewer edgeFunctionsUI = new ComboViewer(parent,
                SWT.SINGLE | SWT.BORDER | SWT.DROP_DOWN | SWT.READ_ONLY);
        edgeFunctionsUI.setContentProvider(new ArrayContentProvider());
        edgeFunctionsUI.setInput(edgeFunctions.keySet());
        edgeFunctionsUI.addSelectionChangedListener(ev -> {
            String selected = SelectionAdapter.on(ev.getSelection()).first(String.class).get();
            EdgeFunction function = edgeFunctions.get(selected);

            // FormDataFactory.on( edgeFunctionContainer ).top(
            // edgeFunctionsUI.getCombo(), 4 )
            // .height( function.preferredHeight() ).left( COLUMN_2 ).right( 100
            // );
            FormDataFactory.on(edgeFunctionContainer).height(function.preferredHeight());

            UIUtils.disposeChildren(edgeFunctionContainer);
            // create panel
            function.createContents(tk, edgeFunctionContainer, selectedSourceFeatureSource);
            // FormDataFactory.on( edgeFunctionContainer ).fill();

            // resize also the top container
            // XXX depends on the parent structure
            ((FormData) parent.getParent().getParent().getLayoutData()).height = preferredHeight()
                    + function.preferredHeight();
            parent.getParent().getParent().getParent().layout();

            this.selectedEdgeFunction = function;
        });

        final Label selectSourceTableLabel = tk.createLabel(parent, i18n.get("selectSourceTable"), SWT.NONE);
        FormDataFactory.on(selectSourceTableLabel).top(15).left(1);
        FormDataFactory.on(sourceFeaturesUI.control()).top(selectSourceTableLabel, 2).left(1);
        final Label selectSourcePropertiesLabel = tk.createLabel(parent, i18n.get("selectSourceProperties"),
                SWT.NONE);
        FormDataFactory.on(selectSourcePropertiesLabel).top(sourceFeaturesUI.control(), 4).left(COLUMN_2);
        FormDataFactory.on(sourcePropertiesUI.control()).top(selectSourcePropertiesLabel, 2).left(COLUMN_2);

        final Label selectEdgeFunctionLabel = tk.createLabel(parent, i18n.get("selectEdgeFunction"), SWT.NONE);
        FormDataFactory.on(selectEdgeFunctionLabel).top(sourcePropertiesUI.control(), 6).left(1);
        FormDataFactory.on(edgeFunctionsUI.getCombo()).top(selectEdgeFunctionLabel, 2).left(1);
        FormDataFactory.on(edgeFunctionContainer).fill().top(edgeFunctionsUI.getCombo(), 4).left(COLUMN_2);

        // event listener
        EventManager.instance().subscribe(this, ifType(EdgeFunctionConfigurationDoneEvent.class,
                ev -> ev.status.get() == Boolean.TRUE && ev.getSource().equals(selectedEdgeFunction)));

        EventManager.instance().subscribe(this, ifType(GraphFunctionConfigurationChangedEvent.class,
                ev -> ev.getSource().equals(SingleSourceNodeGraphFunction.this)));
    } catch (Exception e) {
        StatusDispatcher.handleError("", e);
    }
}

From source file:com.pezzuto.pezzuto.ui.StickyHeaderFragment.java

public void sendSearchProdRequest(String scope, String query) {
    RequestsUtils.sendSearchRequest(getContext(), createSearchJSON(scope, query),
            new Response.Listener<JSONArray>() {
                @Override/*from w ww  .  j  a  v a2 s  .co m*/
                public void onResponse(JSONArray response) {
                    Log.d("response", response.toString());
                    try {
                        JSONArray pr = response.getJSONObject(0).getJSONArray("prodotti");
                        prods.clear();
                        List<Product> products = ParseUtils.parseProducts(pr);
                        if (pr.length() == 0)
                            mListener.setEmptyState(MainActivity.PROD_SEARCH);
                        //category division
                        TreeMap<String, List<Product>> catProducts = new TreeMap<>();
                        for (Product p : products) {
                            String category = p.getCategory();
                            List<Product> pros = new ArrayList<>();
                            if (catProducts.containsKey(category))
                                pros = catProducts.get(category);
                            pros.add(p);
                            p.setLabel(category);
                            catProducts.put(category, pros);
                        }

                        //insert in adapter
                        for (String cat : catProducts.keySet())
                            for (Product p : catProducts.get(cat)) {
                                prods.add(p);
                            }

                        adapterProd.notifyDataSetChanged();
                    } catch (JSONException ex) {
                        ex.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    error.printStackTrace();
                }
            });
}

From source file:org.opendatakit.common.persistence.engine.gae.TaskLockImpl.java

/**
 * Returns the lockId for the lock with the earliest in-the-future expiration
 * timestamp. Whatever lock holds that is considered the winner of the mutex.
 * //  w  ww  . j a  va  2 s.com
 * NOTE: Returning null does not mean there is no active lock. It can mean
 * that the Memcache is unavailable or has been cleared.
 * 
 * @param formId
 * @param taskType
 * @return
 * @throws ODKTaskLockException
 */
private synchronized String queryForLockIdMemCache(String formId, ITaskLockType taskType)
        throws ODKTaskLockException {
    if (syncCache != null) {
        try {
            String formTask = ((formId == null) ? "" : formId) + "@" + taskType.getName();
            IdentifiableValue v = syncCache.contains(formTask) ? syncCache.getIdentifiable(formTask) : null;
            if (v == null || v.getValue() == null) {
                return null;
            } else {
                @SuppressWarnings("unchecked")
                TreeMap<Long, String> tm = (TreeMap<Long, String>) v.getValue();
                Long currentTimestamp = System.currentTimeMillis();
                Long youngestActiveTimestamp = 0L;

                for (Long timestamp : tm.keySet()) {
                    if (timestamp >= currentTimestamp) {
                        if (youngestActiveTimestamp == 0L) {
                            youngestActiveTimestamp = timestamp;
                        } else {
                            // same logic as datastore
                            if (Math.abs(youngestActiveTimestamp - timestamp) < taskType.getMinSettleTime()) {
                                throw new ODKTaskLockException(MULTIPLE_RESULTS_ERROR);
                            }
                            if (youngestActiveTimestamp > timestamp) {
                                youngestActiveTimestamp = timestamp;
                            }
                        }
                    }
                }
                if (youngestActiveTimestamp != 0L) {
                    return tm.get(youngestActiveTimestamp);
                }
                return null;
            }
        } catch (ODKTaskLockException e) {
            throw e;
        } catch (Throwable t) {
            t.printStackTrace();
            log.warn("queryForLockIdMemCache -- ignored exception " + t.toString() + " : " + formId + " "
                    + taskType.getName());
            // ignore
        }
    }
    return null;
}

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

/**
 * Create table of volumetry by profile// w ww.  ja  v  a2s  .  com
 * 
 * @param where place to add table
 * @param titles columns title
 * @param globalMap map getting informations to create table
 * @return table representing volumetry by profile
 */
private StringBuffer createVolByProfileTable(Rectangle where, List titles, TreeMap globalMap) {
    StringBuffer tableHtml = new StringBuffer("<html><body><table border='1'><tr>");
    // first line: titles
    for (int i = 0; i < titles.size(); i++) {
        tableHtml.append("<td>" + (String) titles.get(i) + "</td>");
    }
    tableHtml.append("</tr>");
    // volumetry by profile
    for (Iterator profileIt = globalMap.keySet().iterator(); profileIt.hasNext();) {
        String curProfile = (String) profileIt.next();
        // add cyan line for profile
        tableHtml.append("<tr bgcolor=\"#00FFFF\">");
        tableHtml.append("<td colspan='" + titles.size() + "'>" + curProfile.toUpperCase() + "</td>");
        tableHtml.append("</tr>");
        // get tres
        TreeMap curTres = (TreeMap) globalMap.get(curProfile);
        for (Iterator tresIt = curTres.keySet().iterator(); tresIt.hasNext();) {
            tableHtml.append("<tr>");
            String curTre = (String) tresIt.next();
            tableHtml.append("<td>" + WebMessages.getString(request, curTre) + "</td>");
            // get values for this tre
            ArrayList treLine = (ArrayList) curTres.get(curTre);
            int total = 0;
            for (int i = 0; i < treLine.size(); i++) {
                tableHtml.append("<td>" + (String) treLine.get(i) + "</td>");
                try {
                    total += Integer.parseInt((String) treLine.get(i));
                } catch (NumberFormatException nfe) {
                    // do nothing
                }
            }
            tableHtml.append("<td>" + total + "</td>");
            tableHtml.append("</tr>");
        }
    }
    tableHtml.append("</table></body></html>");
    return tableHtml;
}

From source file:edu.isi.wings.portal.controllers.PlanController.java

private ArrayList<ArrayList<TreeMap<String, Binding>>> getDataBindings(VariableBindingsListSet bindingsets) {
    ArrayList<ArrayList<TreeMap<String, Binding>>> blistsets = new ArrayList<ArrayList<TreeMap<String, Binding>>>();

    for (ArrayList<VariableBindingsList> bindings : bindingsets) {
        HashMap<String, Boolean> bindingstrs = new HashMap<String, Boolean>();
        ArrayList<TreeMap<String, Binding>> blist = new ArrayList<TreeMap<String, Binding>>();
        for (VariableBindingsList binding : bindings) {
            TreeMap<String, Binding> xbindings = new TreeMap<String, Binding>();

            for (VariableBindings vb : binding) {
                String vname = vb.getDataVariable().getName();
                Binding b = new Binding();
                for (KBObject obj : vb.getDataObjects()) {
                    Binding cb = new Binding(obj.getID());
                    if (vb.getDataObjects().size() == 1)
                        b = cb;//from w  w w .j a v  a  2  s . com
                    else
                        b.add(cb);
                }
                xbindings.put(vname, b);
            }
            String bstr = "";
            for (String v : xbindings.keySet()) {
                bstr += xbindings.get(v).toString() + ",";
            }
            if (!bindingstrs.containsKey(bstr)) {
                bindingstrs.put(bstr, true);
                blist.add(xbindings);
            }
        }
        blistsets.add(blist);
    }
    return blistsets;
}

From source file:module.entities.NameFinder.RegexNameFinder.java

public static String getSignatureFromParagraphs(Elements paragraphs) {
    String signature = "";
    String signName = "", roleName = "";
    int signIdx = 0, roleIdx = 0;
    int row = 0;/*from   w w  w  .j  ava  2 s  . c o m*/
    TreeMap<Integer, String> roles = new TreeMap<Integer, String>();
    for (Element n : paragraphs) {
        row++;
        String formatedText = Normalizer.normalize(n.text().toUpperCase(locale), Normalizer.Form.NFD)
                .replaceAll("\\p{M}", "");
        if (formatedText.contains(" ") && !formatedText.matches(".*[0-9].*")) {
            //                  if (formatedText.contains("<br>")) {
            //                      formatedText = formatedText.replaceAll("<br\\s*/>", " ");
            //                   }
            String[] splitedText = formatedText.split(" ");
            //                    System.out.println(splitedText.length);
            if (splitedText.length < 7) {
                boolean isSign = false;
                String text = "";
                for (int z = 0; z < splitedText.length; z++) {
                    String splText = splitedText[z].replaceAll("[\\s.]", "").replaceAll("\u00a0", "")
                            .replaceAll("", "").replaceAll(",", "");
                    if (names.contains(splText) || surnames.contains(splText)) {
                        signName += splText + " ";
                        signIdx = row;
                        isSign = true;
                    }
                    text += splText + " ";
                    //                            if (z == splitedText.length-1){
                    //                                System.out.println(signName.trim());
                    //                            }
                }
                if (!isSign) {
                    roleIdx = row;
                    if (!text.contains(" ") && !text.contains("")) {
                        roles.put(roleIdx, text.trim());
                    }
                }
            }
        }
    }
    for (Integer roleRow : roles.keySet()) {
        //                    if (signName.length() == 0) {
        if (Math.abs(signIdx - roleRow) < 4) {
            roleName += roles.get(roleRow) + " ";
        }

    }

    if (signName.length() > 0) {
        signature = signName + "#" + roleName;
    }
    return signature;
}

From source file:de.nec.nle.siafu.model.DiscreteOverlay.java

/**
 * Create a discrete overlay using the thresholds int he configuration
 * object./*from   ww w  .  java 2 s .  c  o m*/
 * 
 * @param name
 *            the name of the overlay
 * @param is
 *            the InputStream with the image that represents the values
 * @param simulationConfig
 *            the configuration file where the threshold details are given
 */
public DiscreteOverlay(final String name, final InputStream is, final Configuration simulationConfig) {
    super(name, is);

    // A tree to sort the thresholds
    TreeMap<Integer, String> intervals = new TreeMap<Integer, String>();

    // Find out how many thresholds we have
    String[] property;
    try {
        property = simulationConfig.getStringArray("overlays." + name + ".threshold[@tag]");
        if (property.length == 0)
            throw new ConfigurationRuntimeException();
    } catch (ConfigurationRuntimeException e) {
        throw new RuntimeException("You forgot the description of " + name + " in the config file");
    }

    thresholds = new int[property.length];
    tags = new String[property.length];

    // Read the thresholds
    for (int i = 0; i < property.length; i++) {
        String tag = simulationConfig.getString("overlays." + name + ".threshold(" + i + ")[@tag]");
        int pixelValue = simulationConfig.getInt("overlays." + name + ".threshold(" + i + ")[@pixelvalue]");
        intervals.put(pixelValue, tag);
    }

    // Store the sorted thresholds
    int i = 0;
    for (int key : intervals.keySet()) {
        thresholds[i] = key;
        tags[i] = intervals.get(key);
        i++;
    }
}