Example usage for java.util TreeMap containsKey

List of usage examples for java.util TreeMap containsKey

Introduction

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

Prototype

public boolean containsKey(Object key) 

Source Link

Document

Returns true if this map contains a mapping for the specified key.

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");

    System.out.println(treeMap.containsKey("1"));
}

From source file:com.github.xbn.examples.io.non_xbn.SizeOrderAllFilesInDirXmpl.java

public static final void main(String[] ignored) {
    File fDir = (new File("R:\\jeffy\\programming\\sandbox\\xbnjava\\xbn\\"));
    Collection<File> cllf = FileUtils.listFiles(fDir, (new String[] { "java" }), true);

    //Add all file paths to a Map, keyed by size.
    //It's actually a map of lists-of-files, to
    //allow multiple files that happen to have the
    //same length.

    TreeMap<Long, List<File>> tmFilesBySize = new TreeMap<Long, List<File>>();
    Iterator<File> itrf = cllf.iterator();
    while (itrf.hasNext()) {
        File f = itrf.next();//from  w w  w.  j a v a2  s .co  m
        Long LLen = f.length();
        if (!tmFilesBySize.containsKey(LLen)) {
            ArrayList<File> alf = new ArrayList<File>();
            alf.add(f);
            tmFilesBySize.put(LLen, alf);
        } else {
            tmFilesBySize.get(LLen).add(f);
        }
    }

    //Iterate backwards by key through the map. For each
    //List<File>, iterate through the files, printing out
    //its size and path.

    ArrayList<Long> alSize = new ArrayList<Long>(tmFilesBySize.keySet());
    for (int i = alSize.size() - 1; i >= 0; i--) {
        itrf = tmFilesBySize.get(alSize.get(i)).iterator();
        while (itrf.hasNext()) {
            File f = itrf.next();
            System.out.println(f.length() + ": " + f.getPath());
        }
    }
}

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("Checking key value 6");
    System.out.println("Value for key 6 exists: " + treemap.containsKey(6));
}

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("3", "Three");
    treeMap.put("2", "Two");

    Set st = treeMap.keySet();/*from   w  w w.j  a v  a 2s .  co  m*/
    Iterator itr = st.iterator();
    while (itr.hasNext()) {
        System.out.println(itr.next());
    }
    st.remove("1");

    System.out.println(treeMap.containsKey("1"));
}

From source file:com.kaikoda.cah.CardGenerator.java

/**
 * Generates a printable deck of Cards Against Humanity.
 * //from ww w  .ja v  a2  s . com
 * @param args where to find the data file and optionally the dictionary and
 *        target language if translation is required.
 * @throws CardGeneratorConfigurationException when it's not possible to
 *         construct a usable instance of CardGenerator.
 * @throws IOException
 * @throws SAXException
 * @throws ParserConfigurationException
 * @throws ParseException if there are any problems encountered while
 *         parsing the command line tokens.
 */
public static void main(String[] args) throws CardGeneratorConfigurationException, ParseException, SAXException,
        IOException, ParserConfigurationException {

    ProgressReporterMode verbosity = ProgressReporterMode.NORMAL;

    CardGenerator generator = new CardGenerator();
    generator.setVerbosity(verbosity);

    // Configure valid options accepted from the command-line
    CardGeneratorOptions options = new CardGeneratorOptions();

    // Interpret the arguments supplied at runtime.
    TreeMap<String, String> params = options.parse(args);

    // Check whether a level of verbosity has been specified.
    if (params.containsKey("verbosity")) {
        verbosity = ProgressReporterMode.valueOf(params.get("verbosity").toUpperCase());
        generator.setVerbosity(verbosity);
    }

    // Check whether help has been requested.
    if (params.containsKey("help")) {

        if (verbosity.equals(ProgressReporterMode.NORMAL)) {

            // Print a list of the options that can be used with
            // CardGenerator.
            System.out.println("\n" + params.get("help"));

        }

    } else {

        File data = new File(params.remove("path-to-data"));

        CardGeneratorProduct product = CardGeneratorProduct.HTML;
        if (params.containsKey("product")) {
            product = CardGeneratorProduct.valueOf(params.remove("product").toUpperCase());
        }

        Locale targetLanguage = null;
        if (params.containsKey("output-language")) {
            targetLanguage = Locale.forLanguageTag(params.remove("output-language"));
        }

        File dictionary = null;
        if (params.containsKey("path-to-dictionary")) {
            dictionary = new File(params.remove("path-to-dictionary"));
        }

        generator.generate(data, targetLanguage, dictionary, product);

    }
}

From source file:org.grouplens.lenskit.eval.metrics.predict.LastFmEvaluation.java

public static void main(String[] args) {

    String csvFile = "/home/user/Desktop/LastFM_exps/newresultssets/LastFM_1_of_5_20140613-1938.csv";
    //        String csvFile = "/home/user/Desktop/LastFM_exps/reresultset1of5fold/LastFM_1_of_5_20140606-0338.csv";
    BufferedReader br = null;//from  w  w  w. j av  a 2s.c o m
    String sCurrentLine = "";
    String cvsSplitBy = ",";

    try {

        TreeMap<Integer, ArrayList<Double>> golden = new TreeMap<Integer, ArrayList<Double>>();
        TreeMap<Integer, ArrayList<Double>> methodA = new TreeMap<Integer, ArrayList<Double>>();
        TreeMap<Integer, ArrayList<Double>> methodB = new TreeMap<Integer, ArrayList<Double>>();
        TreeMap<Integer, ArrayList<Double>> methodC = new TreeMap<Integer, ArrayList<Double>>();

        br = new BufferedReader(new FileReader(csvFile));
        //            String header = br.readLine();
        //            System.out.println(header);

        while ((sCurrentLine = br.readLine()) != null) {

            String[] cols = sCurrentLine.split(cvsSplitBy);
            int userId = Integer.parseInt(cols[0]);
            double goldenValue = Double.parseDouble(cols[5]);
            double methodAValue = Double.parseDouble(cols[2]);
            double methodBValue = Double.parseDouble(cols[3]);
            double methodCValue = Double.parseDouble(cols[4]);

            //Actual Values TreeMap creation
            if (!golden.containsKey(userId)) {
                golden.put(userId, new ArrayList<Double>());
                golden.get(userId).add(goldenValue);
            } else {
                golden.get(userId).add(goldenValue);
            }
            //Method A TreeMap creation
            if (!methodA.containsKey(userId)) {
                methodA.put(userId, new ArrayList<Double>());
                methodA.get(userId).add(methodAValue);
            } else {
                methodA.get(userId).add(methodAValue);
            }
            //Method B TreeMap creation
            if (!methodB.containsKey(userId)) {
                methodB.put(userId, new ArrayList<Double>());
                methodB.get(userId).add(methodBValue);
            } else {
                methodB.get(userId).add(methodBValue);
            }
            //Method C TreeMap creation
            if (!methodC.containsKey(userId)) {
                methodC.put(userId, new ArrayList<Double>());
                methodC.get(userId).add(methodCValue);
            } else {
                methodC.get(userId).add(methodCValue);
            }

        }

        uniqueUsers = golden.size();
        System.out.println("To synolo twn monadikwn xristwn sto dataset einai: " + uniqueUsers);

        nusers = 0;
        sumPearsonA = 0;
        sumPearsonB = 0;
        sumPearsonC = 0;
        for (Integer i : golden.keySet()) {

            Double[] ADoubles = new Double[methodA.get(i).size()];
            methodA.get(i).toArray(ADoubles);
            Double[] BDoubles = new Double[methodB.get(i).size()];
            methodB.get(i).toArray(BDoubles);
            Double[] CDoubles = new Double[methodC.get(i).size()];
            methodC.get(i).toArray(CDoubles);
            Double[] goldenDoubles = new Double[golden.get(i).size()];
            golden.get(i).toArray(goldenDoubles);

            if (goldenDoubles.length > 1) {

                corA = p.correlation(ArrayUtils.toPrimitive(ADoubles), ArrayUtils.toPrimitive(goldenDoubles));
                corB = p.correlation(ArrayUtils.toPrimitive(BDoubles), ArrayUtils.toPrimitive(goldenDoubles));
                corC = p.correlation(ArrayUtils.toPrimitive(CDoubles), ArrayUtils.toPrimitive(goldenDoubles));

                if (Double.isNaN(corA)) {

                    corA = 1;
                }
                if (Double.isNaN(corB)) {

                    corB = 1;
                }
                if (Double.isNaN(corC)) {

                    corC = 1;
                }

                sumPearsonA += corA;
                sumPearsonB += corB;
                sumPearsonC += corC;
                nusers++;
                //                for (int arrayCounter = 0; arrayCounter < goldenDoubles.length; arrayCounter++) {
                //
                //                    sumA += ADoubles[arrayCounter];
                //                    sumB += BDoubles[arrayCounter];
                //                    sumC += CDoubles[arrayCounter];
                //                    sumGolden += goldenDoubles[arrayCounter];
                //                    
                //                }
                //
                //                avgA = sumA / ADoubles.length;
                //                avgB = sumB / BDoubles.length;
                //                avgC = sumC / CDoubles.length;
                //                avgGolden = sumGolden / goldenDoubles.length;

                //                    System.out.println(sumPearsonA);
                //                    System.out.println(sumPearsonB);
                //                    System.out.println(sumPearsonC);
                //                    System.out.println(nusers);
                //                    System.out.println("----------------------------------");
                //                sumGolden = 0; sumA = 0; sumB = 0; sumC = 0;
            } else {
                System.out.println("User has only ONE rating!!!!! ");
                System.out.println("----------------------------------");
            }
        }

        avgA = sumPearsonA / nusers;
        avgB = sumPearsonB / nusers;
        avgC = sumPearsonC / nusers;

        System.out.println(avgA);
        System.out.println(avgB);
        System.out.println(avgC);
        System.out.println("----------------------------------");

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    System.out.println("Done");
}

From source file:org.grouplens.lenskit.eval.metrics.predict.LastFmWithTags.java

public static void main(String[] args) {

    //        String trainFile = "/home/user/Desktop/LastFM_exps/reresultset1of5fold/Fold_" + fold + "_train.csv";
    //        String testFile = "/home/user/Desktop/LastFM_exps/reresultset1of5fold/Fold_" + fold + "_test.csv";
    //        String userTagsFile = "/home/user/Desktop/LastFM_exps/reresultset1of5fold/user_taggedartists.csv";
    String trainFile = "/home/user/Desktop/LastFM_exps/reresultset1of5fold/train.csv";
    String testFile = "/home/user/Desktop/LastFM_exps/reresultset1of5fold/Fold_" + fold + "_test.csv";
    String userTagsFile = "/home/user/Desktop/LastFM_exps/reresultset1of5fold/tags.csv";
    BufferedReader brTrain = null;
    BufferedReader brTest = null;
    BufferedReader brTags = null;
    String sCurrentLine = "";
    String splitBy = ",";

    try {/*from ww w.j a  va  2  s  .c om*/
        PrintWriter writeEnhancedTrain = new PrintWriter(
                "/home/user/Desktop/LastFM_exps/reresultset1of5fold/EnhancedTrain_fold " + fold + ".txt",
                "UTF-8");

        TreeMap<Integer, ArrayList<Integer[]>> UserArtist = new TreeMap<>();
        TreeMap<Integer, ArrayList<Integer[]>> UserTag = new TreeMap<>();
        Set<Integer> ArtistArtist = new HashSet<>();
        Set<Integer> UserUser = new HashSet<>();
        //            TreeMap<Integer, Integer> ArtistArtist = new TreeMap<>();
        //            TreeMap<Integer, ArrayList<Integer[]>> ArtistTag = new TreeMap<>();

        brTrain = new BufferedReader(new FileReader(trainFile));
        brTest = new BufferedReader(new FileReader(testFile));
        brTags = new BufferedReader(new FileReader(userTagsFile));

        while ((sCurrentLine = brTrain.readLine()) != null) {

            String[] cols = sCurrentLine.split(splitBy);

            int userId = Integer.parseInt(cols[0]);
            int artistId = Integer.parseInt(cols[1]);
            double actualValue = Double.parseDouble(cols[5]);

            Integer[] ArtistValue = new Integer[cols.length - 4];

            for (int i = 1; i < cols.length - 3; i++) {
                if (i != 1) {
                    ArtistValue[i - 1] = Integer.parseInt(cols[i + 3]);
                } else {
                    ArtistValue[i - 1] = Integer.parseInt(cols[i]);
                }
            }

            // Create User --> Artist --> Hits TreeMap
            if (!UserArtist.containsKey(userId)) {
                UserArtist.put(userId, new ArrayList<Integer[]>());
                UserArtist.get(userId).add(ArtistValue);
            } else {
                UserArtist.get(userId).add(ArtistValue);
            }

            // Create User --> User
            //                UserUser.add(userId);
            // Create Artist --> Artist
            ArtistArtist.add(artistId);

        }

        // Print User --> Artist
        for (Integer uid : UserArtist.keySet()) {
            for (Integer[] rows : UserArtist.get(uid)) {
                writeEnhancedTrain.print(uid + " ");
                for (Integer col : rows) {
                    writeEnhancedTrain.print(col.toString() + " ");//rows.toString()
                }
                writeEnhancedTrain.println();
            }
        }

        // Print -Artist --> Artist
        for (Integer art : ArtistArtist) {
            writeEnhancedTrain.println("-" + art + " " + art + " 1");
        }

        // Print -User --> User
        //            for (Integer usr : UserUser) {
        //                writeEnhancedTrain.println("-" + usr + " " + usr + " 1");
        //            }
        // Create Artist --> Tag
        String line = "";
        HashMap<Integer, HashMap<Integer, Integer>> atMap = new HashMap();
        HashMap<Integer, Integer> tcMap = null;// = new HashMap<>();
        HashMap<Integer, HashMap<Integer, Integer>> utMap = new HashMap();
        HashMap<Integer, Integer> hsMap = null;
        String headerLine = brTags.readLine();
        while ((line = brTags.readLine()) != null) {
            String[] cols = line.split(splitBy);
            int userId = Integer.parseInt(cols[0]);
            int artistId = Integer.parseInt(cols[1]);
            int tagId = Integer.parseInt(cols[2]);

            tcMap = atMap.get(artistId);
            if (tcMap == null) {
                tcMap = new HashMap<>();
                tcMap.put(tagId, 1);
                atMap.put(artistId, tcMap);
            } else {
                //                    atMap.put(artistId, tcMap);
                //                    Integer count = atMap.get(artistId).get(tagId);
                //                    count++;
                if (atMap.get(artistId).get(tagId) != null) {
                    tcMap.put(tagId, atMap.get(artistId).get(tagId) + 1);
                    atMap.put(artistId, tcMap);
                } else {
                    System.out.println("To tag den exei ksanaemfanistei!!");
                }
            }

            // Create User --> TagHits
            hsMap = utMap.get(userId);
            if (hsMap == null) {
                hsMap = new HashMap<>();
                hsMap.put(tagId, 0);
                utMap.put(userId, hsMap);
            } else {
                for (Integer uid : UserArtist.keySet()) {
                    for (Integer[] rows : UserArtist.get(uid)) {
                        int aid = rows[0];
                        int hits = rows[1];
                        HashMap tags = atMap.get(artistId);
                        Set alltags = tags.keySet();
                        for (Object tid : alltags) {
                            try {
                                Integer a = utMap.get(uid).get(tagId);
                                if (a == null) {
                                    utMap.get(uid).put((Integer) tid, hits);
                                } else {
                                    utMap.get(uid).put((Integer) tid, hits + a);
                                }
                            } catch (java.lang.NullPointerException er) {
                                System.out.println(er);//er.printStackTrace();
                            }
                        }
                    }
                }
            }

        }

        // Print Artist --> Tag
        for (Integer atMapEntry : atMap.keySet()) {
            Integer artid = atMapEntry;
            for (Integer tcMapEntry : tcMap.keySet()) {
                Integer tagid = tcMapEntry;
                Integer tagCounter = tcMap.get(atMapEntry);
                writeEnhancedTrain.println(artid + " " + tagid + " " + tagCounter);
            }
        }

        // Print User --> TagHits
        for (Integer userTagHits : utMap.keySet()) {
            Integer user = userTagHits;
            for (Integer hsCounter : hsMap.keySet()) {
                Integer tag = hsCounter;
                Integer hits = hsMap.get(userTagHits);
                writeEnhancedTrain.println(user + " " + tag + " " + hits);
            }
        }

        //            System.out.println(ArtistArtist.size());
        //            System.out.println(UserUser.size());
        writeEnhancedTrain.flush();
        writeEnhancedTrain.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (brTrain != null) {
            try {
                brTrain.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    System.out.println("Done");
}

From source file:eval.dataset.ParseWikiLog.java

private static void updateMap(TreeMap<String, Set<String>> userPageMap, String user, String page) {
    if (userPageMap.containsKey(user)) {
        userPageMap.get(user).add(page);
    } else {//w  w  w  . j  a v a 2  s .c om
        Set<String> pageSet = new TreeSet();
        pageSet.add(page);
        userPageMap.put(user, pageSet);
    }

}

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.//from   w ww.  j a va  2 s . c o  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:com.opengamma.analytics.financial.provider.calculator.discounting.CashFlowEquivalentCalculator.java

/**
 * Add a cash flow amount at a given time in the flow map. If the time is present, the amount is added; if the time is not present a new entry is created.
 * @param flow The map describing the cash flows.
 * @param time The time of the flow to add.
 * @param amount The amount of the flow to add.
 *///from  w w  w  .ja  v a  2  s  .c  o  m
private static void addcf(final TreeMap<Double, Double> flow, final double time, final double amount) {
    if (flow.containsKey(time)) {
        flow.put(time, flow.get(time) + amount);
    } else {
        flow.put(time, amount);
    }
}