Example usage for java.util TreeSet contains

List of usage examples for java.util TreeSet contains

Introduction

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

Prototype

public boolean contains(Object o) 

Source Link

Document

Returns true if this set contains the specified element.

Usage

From source file:Main.java

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

    boolean blnExists = tSet.contains("3");
    System.out.println("3 exists in TreeSet ? : " + blnExists);
}

From source file:Main.java

public static void main(String[] args) {

    TreeSet<Integer> treeadd = new TreeSet<Integer>();

    treeadd.add(12);//from w  w w .j  a  v a2s. c o  m
    treeadd.add(13);
    treeadd.add(14);
    treeadd.add(15);

    // check existence of 15  
    System.out.println("Checking existence of 15 ");
    System.out.println("Is 15 there in the set: " + treeadd.contains(15));
}

From source file:se.lth.cs.nlp.wikiforia.App.java

/**
 * Application entrypoint/*from   w  w w.  j av  a2  s  .  c o m*/
 * @param args input arguments
 */
public static void main(String[] args) {
    Logger logger = LoggerFactory.getLogger(App.class);

    logger.info("Wikiforia v1.1.1 by Marcus Klang");

    Options options = new Options();
    options.addOption(index);
    options.addOption(pages);
    options.addOption(threads);
    options.addOption(batch);
    options.addOption(output);
    options.addOption(lang);
    options.addOption(hadoop);
    options.addOption(gzip);
    options.addOption(filterNs);

    CommandLineParser parser = new PosixParser();
    try {
        CommandLine cmdline = parser.parse(options, args);

        File indexPath = null, pagesPath, outputPath;
        int batchsize = 100;
        int numThreads = Runtime.getRuntime().availableProcessors();

        //Read batch size
        if (cmdline.hasOption(batch.getOpt())) {
            batchsize = Integer.parseInt(cmdline.getOptionValue(batch.getOpt()));
        }

        //Read num threads
        if (cmdline.hasOption(threads.getOpt())) {
            numThreads = Integer.parseInt(cmdline.getOptionValue(threads.getOpt()));
        }

        //Read required paths
        pagesPath = new File(cmdline.getOptionValue(pages.getOpt()));
        outputPath = new File(cmdline.getOptionValue(output.getOpt()));

        //Create output directories if they do not exist
        if (!outputPath.getParentFile().getAbsoluteFile().exists()) {
            if (!outputPath.getParentFile().getAbsoluteFile().mkdirs()) {
                throw new IOError(new IOException(
                        "Failed to create directories for " + outputPath.getParentFile().getAbsolutePath()));
            }
        }

        //To to automatically select an index file if it does not exits
        if (!cmdline.hasOption(index.getOpt())) {
            //try to automatically identify if there is an index file
            if (pagesPath.getAbsolutePath().toLowerCase().endsWith("-multistream.xml.bz2")) {
                int pos = pagesPath.getAbsolutePath().lastIndexOf("-multistream.xml.bz2");
                indexPath = new File(
                        pagesPath.getAbsolutePath().substring(0, pos) + "-multistream-index.txt.bz2");
                if (!indexPath.exists())
                    indexPath = null;
            }
        } else {
            indexPath = new File(cmdline.getOptionValue(index.getOpt()));
        }

        //Validation
        if (!pagesPath.exists()) {
            logger.error("pages with absolute filepath {} could not be found.", pagesPath.getAbsolutePath());
            return;
        }

        if (indexPath != null && !indexPath.exists()) {
            logger.error("Could not find index file {}.", indexPath.getAbsolutePath());
            logger.error("Skipping index and continuing with singlestream parsing (no threaded decompression)");
            indexPath = null;
        }

        String langId;
        if (cmdline.hasOption(lang.getOpt())) {
            langId = cmdline.getOptionValue(lang.getOpt());
        } else {
            Pattern langmatcher = Pattern.compile("([a-z]{2})wiki-");
            Matcher matcher = langmatcher.matcher(pagesPath.getName());
            if (matcher.find()) {
                langId = matcher.group(1).toLowerCase();
            } else {
                logger.error("Could not find a suitable language, will default to English");
                langId = "en";
            }
        }

        ArrayList<Filter<WikipediaPage>> filters = new ArrayList<Filter<WikipediaPage>>();
        if (cmdline.hasOption(filterNs.getOpt())) {
            String optionValue = cmdline.getOptionValue(filterNs.getOpt());
            final TreeSet<Integer> ns = new TreeSet<Integer>();
            for (String s : optionValue.split(",")) {
                ns.add(Integer.parseInt(s));
            }

            if (ns.size() > 0) {
                filters.add(new Filter<WikipediaPage>() {
                    @Override
                    protected boolean accept(WikipediaPage item) {
                        return ns.contains(item.getNamespace());
                    }

                    @Override
                    public String toString() {
                        return String.format("Namespace filter { namespaces: %s }", StringUtils.join(ns, ","));
                    }
                });
            }
        }

        TemplateConfig config;
        if (langId.equals("sv")) {
            config = new SwedishConfig();
        } else if (langId.equals("en")) {
            config = new EnglishConfig();
        } else {
            config = new EnglishConfig();
            logger.error(
                    "language {} is not yet supported and will be defaulted to a English setting for Sweble.",
                    langId);
            langId = "en";
        }

        if (cmdline.hasOption(hadoop.getOpt())) {
            if (outputPath.exists()) {
                logger.error("The target location already exists, please remove before using the tool!");
                System.exit(1);
            } else {
                int splitsize = 64000000;
                if (cmdline.hasOption(App.splitsize.getOpt())) {
                    splitsize = Integer.parseInt(cmdline.getOptionValue(App.splitsize.getOpt()));
                }

                hadoopConvert(config, indexPath, pagesPath, outputPath, numThreads, batchsize, splitsize,
                        cmdline.hasOption(gzip.getOpt()), filters);
            }
        } else {
            convert(config, indexPath, pagesPath, outputPath, numThreads, batchsize, filters);
        }

    } catch (ParseException e) {
        System.out.println(e.getMessage());
        HelpFormatter writer = new HelpFormatter();
        writer.printHelp("wikiforia", options);
    }
}

From source file:nlp.wikiforia.App.java

/**
 * Application entrypoint//from w  w w  .j  a  v  a  2 s .co m
 * @param args input arguments
 */
public static void main(String[] args) {
    Logger logger = LoggerFactory.getLogger(App.class);

    logger.info("Wikiforia v1.2.1 by Marcus Klang");

    Options options = new Options();
    options.addOption(index);
    options.addOption(pages);
    options.addOption(threads);
    options.addOption(batch);
    options.addOption(output);
    options.addOption(lang);
    options.addOption(hadoop);
    options.addOption(gzip);
    options.addOption(testDecompression);
    options.addOption(filterNs);
    options.addOption(outputFormatOption);

    CommandLineParser parser = new PosixParser();
    try {
        CommandLine cmdline = parser.parse(options, args);

        File indexPath = null, pagesPath, outputPath;
        int batchsize = 100;
        int numThreads = Runtime.getRuntime().availableProcessors();
        String outputFormat = OUTPUT_FORMAT_DEFAULT;

        //Read batch size
        if (cmdline.hasOption(batch.getOpt())) {
            batchsize = Integer.parseInt(cmdline.getOptionValue(batch.getOpt()));
        }

        //Read num threads
        if (cmdline.hasOption(threads.getOpt())) {
            numThreads = Integer.parseInt(cmdline.getOptionValue(threads.getOpt()));
        }

        //Output format
        if (cmdline.hasOption(outputFormatOption.getOpt())) {
            outputFormat = cmdline.getOptionValue(outputFormatOption.getOpt());
        }

        //Read required paths
        pagesPath = new File(cmdline.getOptionValue(pages.getOpt()));
        outputPath = new File(cmdline.getOptionValue(output.getOpt()));

        //Create output directories if they do not exist
        if (!outputPath.getAbsoluteFile().getParentFile().getAbsoluteFile().exists()) {
            if (!outputPath.getParentFile().getAbsoluteFile().mkdirs()) {
                throw new IOError(new IOException(
                        "Failed to create directories for " + outputPath.getParentFile().getAbsolutePath()));
            }
        }

        //To to automatically select an index file if it does not exits
        if (!cmdline.hasOption(index.getOpt())) {
            //try to automatically identify if there is an index file
            if (pagesPath.getAbsolutePath().toLowerCase().endsWith("-multistream.xml.bz2")) {
                int pos = pagesPath.getAbsolutePath().lastIndexOf("-multistream.xml.bz2");
                indexPath = new File(
                        pagesPath.getAbsolutePath().substring(0, pos) + "-multistream-index.txt.bz2");
                if (!indexPath.exists())
                    indexPath = null;
            }
        } else {
            indexPath = new File(cmdline.getOptionValue(index.getOpt()));
        }

        //Validation
        if (!pagesPath.exists()) {
            logger.error("pages with absolute filepath {} could not be found.", pagesPath.getAbsolutePath());
            return;
        }

        if (indexPath != null && !indexPath.exists()) {
            logger.error("Could not find index file {}.", indexPath.getAbsolutePath());
            logger.error("Skipping index and continuing with singlestream parsing (no threaded decompression)");
            indexPath = null;
        }

        String langId;
        if (cmdline.hasOption(lang.getOpt())) {
            langId = cmdline.getOptionValue(lang.getOpt());
        } else {
            Pattern langmatcher = Pattern.compile("([a-z]{2})wiki-");
            Matcher matcher = langmatcher.matcher(pagesPath.getName());
            if (matcher.find()) {
                langId = matcher.group(1).toLowerCase();
            } else {
                logger.error("Could not find a suitable language, will default to English");
                langId = "en";
            }
        }

        ArrayList<Filter<WikipediaPage>> filters = new ArrayList<Filter<WikipediaPage>>();
        if (cmdline.hasOption(filterNs.getOpt())) {
            String optionValue = cmdline.getOptionValue(filterNs.getOpt());
            final TreeSet<Integer> ns = new TreeSet<Integer>();
            for (String s : optionValue.split(",")) {
                ns.add(Integer.parseInt(s));
            }

            if (ns.size() > 0) {
                filters.add(new Filter<WikipediaPage>() {
                    @Override
                    protected boolean accept(WikipediaPage item) {
                        return ns.contains(item.getNamespace());
                    }

                    @Override
                    public String toString() {
                        return String.format("Namespace filter { namespaces: %s }", StringUtils.join(ns, ","));
                    }
                });
            }
        }

        TemplateConfig config;
        Class<? extends TemplateConfig> configClazz = LangFactory.get(langId);
        if (configClazz != null) {
            try {
                config = configClazz.newInstance();
            } catch (InstantiationException e) {
                throw new RuntimeException(e);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        } else {
            config = new EnglishConfig();
            logger.error(
                    "language {} is not yet supported and will be defaulted to a English setting for Sweble.",
                    langId);
            langId = "en";
        }

        if (cmdline.hasOption(hadoop.getOpt())) {
            if (outputPath.exists()) {
                logger.error("The target location already exists, please remove before using the tool!");
                System.exit(1);
            } else {
                int splitsize = 64000000;
                if (cmdline.hasOption(App.splitsize.getOpt())) {
                    splitsize = Integer.parseInt(cmdline.getOptionValue(App.splitsize.getOpt()));
                }

                hadoopConvert(config, indexPath, pagesPath, outputPath, numThreads, batchsize, splitsize,
                        cmdline.hasOption(gzip.getOpt()), filters);
            }
        } else {
            if (cmdline.hasOption(testDecompression.getOpt())) {
                test(config, indexPath, pagesPath, numThreads, batchsize);
            } else {
                convert(config, indexPath, pagesPath, outputPath, numThreads, batchsize, filters, outputFormat);
            }
        }

    } catch (ParseException e) {
        System.out.println(e.getMessage());
        HelpFormatter writer = new HelpFormatter();
        writer.printHelp("wikiforia", options);
    }
}

From source file:nl.mpi.tla.isle2clarin.Main.java

public static void main(String[] args) {
    try {//w  w  w  . ja  va  2  s  .com
        // initialize CMDI2IMDI
        boolean validateIMDI = false;
        boolean validateCMDI = false;
        TreeSet<String> skip = new TreeSet<>();
        Translator imdi2cmdi = new TranslatorImpl();
        SchemAnon tron = new SchemAnon(Main.class.getResource("/IMDI_3.0.xsd"));
        // check command line
        OptionParser parser = new OptionParser("ics:?*");
        OptionSet options = parser.parse(args);
        if (options.has("i"))
            validateIMDI = true;
        if (options.has("c"))
            validateCMDI = true;
        if (options.has("s"))
            skip = loadSkipList((String) options.valueOf("s"));
        if (options.has("?")) {
            showHelp();
            System.exit(0);
        }
        List arg = options.nonOptionArguments();
        if (arg.size() < 1 && arg.size() > 2) {
            System.err.println("FTL: none or too many non-option arguments!");
            showHelp();
            System.exit(1);
        }
        if (arg.size() > 1) {
            if (options.has("s")) {
                System.err.println("FTL: -s option AND <FILE> argument, use only one!");
                showHelp();
                System.exit(1);
            }
            skip = loadSkipList((String) arg.get(1));
        }
        Collection<File> inputs = null;
        File in = new File((String) arg.get(0));
        if (in.isDirectory()) {
            inputs = FileUtils.listFiles(in, new String[] { "imdi" }, true);
        } else if (in.isFile()) {
            inputs = loadInputList(in);
        } else {
            System.err.println("FTL: unknown type of <INPUT>!");
            showHelp();
            System.exit(1);
        }
        int i = 0;
        int s = inputs.size();
        for (File input : inputs) {
            i++;
            try {
                String path = input.getAbsolutePath();
                //System.err.println("DBG: absolute path["+path+"]");
                //System.err.println("DBG: relative path["+path.replaceAll("^" + in.getAbsolutePath() + "/", "")+"]");
                if (input.isHidden()) {
                    System.err.println("WRN:" + i + "/" + s + ": file[" + path + "] is hidden, skipping it.");
                    continue;
                } else if (path.matches(".*/(corpman|sessions)/.*")) {
                    System.err.println("WRN:" + i + "/" + s + ": file[" + path
                            + "] is in a corpman or sessions dir, skipping it.");
                    continue;
                } else if (skip.contains(path.replaceAll("^" + in.getAbsolutePath() + "/", ""))) {
                    System.err.println(
                            "WRN:" + i + "/" + s + ": file[" + path + "] is in the skip list, skipping it.");
                    continue;
                } else if (skip.contains(path)) {
                    System.err.println(
                            "WRN:" + i + "/" + s + ": file[" + path + "] is in the skip list, skipping it.");
                    continue;
                } else
                    System.err.println("DBG:" + i + "/" + s + ": convert file["
                            + path.replaceAll("^" + (String) arg.get(0) + "/", "") + "]");
                if (validateIMDI) {
                    // validate IMDI
                    if (!tron.validate(input)) {
                        System.err.println(
                                "ERR:" + i + "/" + s + ": invalid file[" + input.getAbsolutePath() + "]");
                        for (Message msg : tron.getMessages()) {
                            System.out.println("" + (msg.isError() ? "ERR: " : "WRN: ") + i + "/" + s + ": "
                                    + (msg.getLocation() != null ? "at " + msg.getLocation() : ""));
                            System.out.println("" + (msg.isError() ? "ERR: " : "WRN: ") + i + "/" + s + ": "
                                    + msg.getText());
                        }
                    } else
                        System.err.println(
                                "DBG:" + i + "/" + s + ": valid file[" + input.getAbsolutePath() + "]");
                }
                // IMDI 2 CMDI
                File output = new File(input.getAbsolutePath().replaceAll("\\.imdi$", ".cmdi"));
                PrintWriter out = new PrintWriter(output.getAbsolutePath());
                Map<String, Object> params = new HashMap<>();
                params.put("formatCMDI", Boolean.FALSE);
                imdi2cmdi.setTransformationParameters(params);
                out.print(imdi2cmdi.getCMDI(input.toURI().toURL(), ""));
                out.close();
                System.err.println("DBG:" + i + "/" + s + ": wrote   file[" + output.getAbsolutePath() + "]");
                if (validateCMDI) {
                    CMDIValidatorConfig.Builder builder = new CMDIValidatorConfig.Builder(output,
                            new Handler());
                    CMDIValidator validator = new CMDIValidator(builder.build());
                    SimpleCMDIValidatorProcessor processor = new SimpleCMDIValidatorProcessor();
                    processor.process(validator);
                }
            } catch (Exception ex) {
                System.err.println("ERR:" + i + "/" + s + ":" + input + ":" + ex);
                ex.printStackTrace(System.err);
            }
        }
    } catch (Exception ex) {
        System.err.println("FTL: " + ex);
        ex.printStackTrace(System.err);
    }
}

From source file:org.mrgeo.cmd.generatekeys.GenerateKeys.java

private static List<Integer> findRandomIndices(int num, int indexMin, int indexMax, Random r) {
    log.info("Start generating random indices");

    int range = (indexMax - indexMin) + 1;
    log.info(String.format("Using index range %d %d", indexMin, indexMax));
    TreeSet<Integer> indices = new TreeSet<Integer>();

    while (indices.size() < num) {
        int index = r.nextInt(range) + indexMin;
        if (!indices.contains(index))
            indices.add(index);/* ww w  .  j a v a2 s. c o  m*/
    }

    List<Integer> indicesList = new ArrayList<Integer>();
    for (Integer index : indices)
        indicesList.add(index);
    for (Integer index : indicesList)
        log.info("Index = " + index);
    log.info("End generating random indices");

    return indicesList;
}

From source file:com.hp.alm.ali.idea.cfg.AliConfigurable.java

private static boolean containsInsensitive(Collection<String> c, String val) {
    TreeSet<String> ts = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
    ts.addAll(c);/*from  ww w  . j a va2 s.com*/
    return ts.contains(val);
}

From source file:base.Engine.java

static Set<TreeSet<PatternInstance>> resolveTree(Set<TreeSet<PatternInstance>> returnSet,
        Set<PatternInstance> colls) {
    TreeSet<PatternInstance> workingTree = new TreeSet<>(new InstanceComparator());
    for (PatternInstance p : colls) {
        TreeSet<PatternInstance> onThisTree = null;
        for (TreeSet<PatternInstance> it : returnSet) {
            if (it.contains(p)) {
                onThisTree = it;// w w w .  j  a va2 s  .  com
                break;
            }
        }

        if (onThisTree == null) {
            workingTree.add(p);
        } else {
            workingTree.addAll(onThisTree);
            returnSet.remove(onThisTree);
        }
    }
    returnSet.add(workingTree);
    return returnSet;
}

From source file:base.Engine.java

static Set<TreeSet<PatternInstance>> addPair(Set<TreeSet<PatternInstance>> returnSet, PatternInstance p1,
        PatternInstance p2) {//from  ww  w.  ja v a  2  s . co  m
    TreeSet<PatternInstance> t1 = null;
    TreeSet<PatternInstance> t2 = null;
    for (TreeSet<PatternInstance> aTree : returnSet) {
        if (aTree.contains(p1)) {
            t1 = aTree;
            break;
        }
    }
    for (TreeSet<PatternInstance> aTree : returnSet) {
        if (aTree.contains(p2)) {
            t2 = aTree;
            break;
        }
    }

    if (t1 == null && t2 == null) {
        TreeSet<PatternInstance> newTree = new TreeSet<>(new InstanceComparator());
        newTree.add(p1);
        newTree.add(p2);
        returnSet.add(newTree);
    } else if (t1 == null && t2 != null) {
        t2.add(p1);
    } else if (t1 != null && t2 == null) {
        t1.add(p2);
    } else if (t1 != t2) {
        t1.addAll(t2);
        returnSet.remove(t2);
    }
    return returnSet;
}

From source file:base.Engine.java

static LinkedList<PatternInstance> massMerge(Set<TreeSet<PatternInstance>> collisions,
        LinkedList<PatternInstance> instances, ReferenceMap<PatternWrapper, PatternEntry> knownPatterns,
        Ruleset rule) {//from  www  .  jav a2  s  .c o  m
    PatternInstance currentInstances = null;
    for (ListIterator<PatternInstance> i = instances.listIterator(); i.hasNext();) {
        currentInstances = i.next();
        boolean shouldRemove = false;
        for (TreeSet<PatternInstance> groups : collisions) {
            if (groups.contains(currentInstances)) {
                shouldRemove = true;
                break;
            }
        }
        if (shouldRemove)
            i.remove();
    }

    for (TreeSet<PatternInstance> group : collisions) {
        TreeSet<PatternInstance> runningParts = group;
        boolean stillFindingParts = true;

        while (stillFindingParts) {
            stillFindingParts = false;

            eachMatchLoop: for (PatternInstance part1 : runningParts)
                for (PatternInstance part2 : runningParts)
                    if (part1 != part2 && part1.collides(rule, part2)) {
                        stillFindingParts = true;
                        runningParts.remove(part1);
                        runningParts.remove(part2);
                        runningParts.add(part1.merge(knownPatterns, part2));
                        break eachMatchLoop;
                    }
        }

        for (PatternInstance part : runningParts) {
            instances.add(part);
        }
    }

    return instances;

}