Example usage for java.util TreeMap values

List of usage examples for java.util TreeMap values

Introduction

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

Prototype

public Collection<V> values() 

Source Link

Document

Returns a Collection view of the values contained in this map.

Usage

From source file:Main.java

public static void main(String[] args) {
    TreeMap<String, String> treeMap = new TreeMap<String, String>();
    treeMap.put("1", "One");
    treeMap.put("2", "Two");
    treeMap.put("3", "Three");

    Collection c = treeMap.values();
    Iterator itr = c.iterator();//from   ww w . j  a v  a  2s .  co m

    while (itr.hasNext()) {
        System.out.println(itr.next());
    }
}

From source file:org.jodconverter.document.DumpJsonDefaultDocumentFormatRegistry.java

public static void main(final String[] args) throws Exception {

    final DocumentFormatRegistry registry = DefaultDocumentFormatRegistry.getInstance();
    @SuppressWarnings("unchecked")
    final TreeMap<String, DocumentFormat> formats = new TreeMap<>(
            (Map<String, DocumentFormat>) FieldUtils.readField(registry, "fmtsByExtension", true));

    final Gson gson = new GsonBuilder().setPrettyPrinting().create();
    LOGGER.info(gson.toJson(formats.values()));
}

From source file:Main.java

public static void main(String[] args) {

    TreeMap<Integer, String> treemap = new TreeMap<Integer, String>();

    // populating tree map
    treemap.put(2, "two");
    treemap.put(1, "one");
    treemap.put(3, "three");
    treemap.put(6, "six");
    treemap.put(5, "from java2s.com");

    System.out.println("Getting collection from the map");
    Collection<String> coll = treemap.values();
    System.out.println("Value of the collection: " + coll);
}

From source file:TwitterClustering.java

public static void main(String[] args) throws FileNotFoundException, IOException {
    // TODO code application logic here

    File outFile = new File(args[3]);
    Scanner s = new Scanner(new File(args[1])).useDelimiter(",");
    JSONParser parser = new JSONParser();
    Set<Cluster> clusterSet = new HashSet<Cluster>();
    HashMap<String, Tweet> tweets = new HashMap();
    FileWriter fw = new FileWriter(outFile.getAbsoluteFile());
    BufferedWriter bw = new BufferedWriter(fw);

    // init/*from  ww w. j av a  2  s  .c o  m*/
    try {

        Object obj = parser.parse(new FileReader(args[2]));

        JSONArray jsonArray = (JSONArray) obj;

        for (int i = 0; i < jsonArray.size(); i++) {

            Tweet twt = new Tweet();
            JSONObject jObj = (JSONObject) jsonArray.get(i);
            String text = jObj.get("text").toString();

            long sum = 0;
            for (int y = 0; y < text.toCharArray().length; y++) {

                sum += (int) text.toCharArray()[y];
            }

            String[] token = text.split(" ");
            String tID = jObj.get("id").toString();

            Set<String> mySet = new HashSet<String>(Arrays.asList(token));
            twt.setAttributeValue(sum);
            twt.setText(mySet);
            twt.setTweetID(tID);
            tweets.put(tID, twt);

        }

        // preparing initial clusters
        int i = 0;
        while (s.hasNext()) {
            String id = s.next();// id
            Tweet t = tweets.get(id.trim());
            clusterSet.add(new Cluster(i + 1, t, new LinkedList()));
            i++;
        }

        Iterator it = tweets.entrySet().iterator();

        for (int l = 0; l < 2; l++) { // limit to 25 iterations

            while (it.hasNext()) {
                Map.Entry me = (Map.Entry) it.next();

                // calculate distance to each centroid
                Tweet p = (Tweet) me.getValue();
                HashMap<Cluster, Float> distMap = new HashMap();

                for (Cluster clust : clusterSet) {

                    distMap.put(clust, jaccardDistance(p.getText(), clust.getCentroid().getText()));
                }

                HashMap<Cluster, Float> sorted = (HashMap<Cluster, Float>) sortByValue(distMap);

                sorted.keySet().iterator().next().getMembers().add(p);

            }

            // calculate new centroid and update Clusterset
            for (Cluster clust : clusterSet) {

                TreeMap<String, Long> tDistMap = new TreeMap();

                Tweet newCentroid = null;
                Long avgSumDist = new Long(0);
                for (int j = 0; j < clust.getMembers().size(); j++) {

                    avgSumDist += clust.getMembers().get(j).getAttributeValue();
                    tDistMap.put(clust.getMembers().get(j).getTweetID(),
                            clust.getMembers().get(j).getAttributeValue());
                }
                if (clust.getMembers().size() != 0) {
                    avgSumDist /= (clust.getMembers().size());
                }

                ArrayList<Long> listValues = new ArrayList<Long>(tDistMap.values());

                if (tDistMap.containsValue(findClosestNumber(listValues, avgSumDist))) {
                    // found closest
                    newCentroid = tweets
                            .get(getKeyByValue(tDistMap, findClosestNumber(listValues, avgSumDist)));
                    clust.setCentroid(newCentroid);
                }

            }

        }
        // create an iterator
        Iterator iterator = clusterSet.iterator();

        // check values
        while (iterator.hasNext()) {

            Cluster c = (Cluster) iterator.next();
            bw.write(c.getId() + "\t");
            System.out.print(c.getId() + "\t");

            for (Tweet t : c.getMembers()) {
                bw.write(t.getTweetID() + ", ");
                System.out.print(t.getTweetID() + ",");

            }
            bw.write("\n");
            System.out.println("");
        }

        System.out.println("");

        System.out.println("SSE " + sumSquaredErrror(clusterSet));

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        bw.close();
        fw.close();
    }
}

From source file:com.bluexml.tools.miscellaneous.Translate.java

public static void prapareFileToTranslate(File input, File outDir) throws IOException {
    // create file that contains only text
    File output = new File(outDir, input.getName() + ".txt");

    TreeMap<String, String> props = loadProperties(input);
    Collection<String> lines = props.values();

    FileUtils.writeLines(output, "UTF-8", lines);
}

From source file:Util.java

/**
 * Returns an array of indices indicating the order the data should be sorted
 * in. Duplicate values are discarded with the first one being kept. This method
 * is useful when a number of data arrays have to be sorted based on the values in
 * some coordinate array, such as time./* www. j  a v a  2  s.  co  m*/
 *
 * To convert a array of values to a sorted monooic array try: <br>
 *    double[] x;  // some 1-D array of data <br>
 *    int[] i = MathUtilities.uniqueSort(x); <br>
 *    double[] xSorted = MathUtilities.orderVector(x, i);<br><br>
 *
 * @param x An array of data that is to be sorted.
 * @return order An array of indexes such that y = Array.sort(x) and
 * y = x(order) are the same.
 */
public static final synchronized int[] uniqueSort(double[] x) {
    TreeMap tm = new TreeMap();
    for (int i = 0; i < x.length; i++) {
        Double key = new Double(x[i]);
        boolean exists = tm.containsKey(key);
        if (exists) {
            // Do nothing. Ignore duplicate keys
        } else {
            tm.put(key, new Integer(i));
        }
    }
    Object[] values = tm.values().toArray();
    int[] order = new int[values.length];
    for (int i = 0; i < values.length; i++) {
        Integer tmp = (Integer) values[i];
        order[i] = tmp.intValue();
    }
    return order;
}

From source file:tor.HiddenService.java

public static OnionRouter[] findResposibleDirectories(String onionb32) {
    Consensus con = Consensus.getConsensus();

    // get list of nodes with HS dir flag
    TreeMap<String, OnionRouter> routers = con.getORsWithFlag("HSDir");
    Object keys[] = routers.keySet().toArray();
    Object vals[] = routers.values().toArray();

    ArrayList<OnionRouter> rts = new ArrayList<>();

    for (int replica = 0; replica < 2; replica++) {
        // Get nodes just to right of HS's descID in the DHT
        int idx = -Arrays.binarySearch(keys, Hex.encodeHexString(getDescId(onionb32, (byte) replica)));

        for (int i = 0; i < 3; i++) {
            rts.add((OnionRouter) vals[(idx + i) % vals.length]);
        }/*from   w w  w.ja  v a 2  s  .c om*/
    }

    // return list containing hopefully six ORs.
    return rts.toArray(new OnionRouter[0]);
}

From source file:org.zenoss.zep.index.impl.EventIndexRebuilderImpl.java

private static byte[] calculateIndexVersionHash(Map<String, EventDetailItem> detailItems) throws ZepException {
    TreeMap<String, EventDetailItem> sorted = new TreeMap<String, EventDetailItem>(detailItems);
    StringBuilder indexConfigStr = new StringBuilder();
    for (EventDetailItem item : sorted.values()) {
        // Only key and type affect the indexing behavior - ignore changes to display name
        indexConfigStr.append('|');
        indexConfigStr.append(item.getKey());
        indexConfigStr.append('|');
        indexConfigStr.append(item.getType().name());
        indexConfigStr.append('|');
    }//from w w w.ja  va  2 s. com
    if (indexConfigStr.length() == 0) {
        return null;
    }
    return DaoUtils.sha1(indexConfigStr.toString());
}

From source file:org.dspace.app.xmlui.aspect.discovery.DiscoveryUIUtils.java

public static List<String> getRepeatableParameters(Request request, String prefix) {
    TreeMap<String, String> result = new TreeMap<String, String>();

    Enumeration parameterNames = request.getParameterNames();
    while (parameterNames.hasMoreElements()) {
        String parameter = (String) parameterNames.nextElement();
        if (parameter.startsWith(prefix)) {
            result.put(parameter, request.getParameter(parameter));
        }//from   www  .j a v a2 s  . co m
    }
    return new ArrayList<String>(result.values());
}

From source file:com.uber.hoodie.hadoop.realtime.AbstractRealtimeRecordReader.java

/**
 * Given a comma separated list of field names and positions at which they appear on Hive, return
 * a ordered list of field names, that can be passed onto storage.
 *//*from w  w w  . j  av  a2 s.  c  o m*/
public static List<String> orderFields(String fieldNameCsv, String fieldOrderCsv,
        String partitioningFieldsCsv) {

    String[] fieldOrders = fieldOrderCsv.split(",");
    Set<String> partitioningFields = Arrays.stream(partitioningFieldsCsv.split(","))
            .collect(Collectors.toSet());
    List<String> fieldNames = Arrays.stream(fieldNameCsv.split(","))
            .filter(fn -> !partitioningFields.contains(fn)).collect(Collectors.toList());

    // Hive does not provide ids for partitioning fields, so check for lengths excluding that.
    if (fieldNames.size() != fieldOrders.length) {
        throw new HoodieException(
                String.format("Error ordering fields for storage read. #fieldNames: %d, #fieldPositions: %d",
                        fieldNames.size(), fieldOrders.length));
    }
    TreeMap<Integer, String> orderedFieldMap = new TreeMap<>();
    for (int ox = 0; ox < fieldOrders.length; ox++) {
        orderedFieldMap.put(Integer.parseInt(fieldOrders[ox]), fieldNames.get(ox));
    }
    return new ArrayList<>(orderedFieldMap.values());
}