Example usage for java.util HashSet HashSet

List of usage examples for java.util HashSet HashSet

Introduction

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

Prototype

public HashSet() 

Source Link

Document

Constructs a new, empty set; the backing HashMap instance has default initial capacity (16) and load factor (0.75).

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setValidating(false);/*www . ja v  a2  s . c  o m*/
    domFactory.setNamespaceAware(true);
    domFactory.setIgnoringComments(true);
    domFactory.setIgnoringElementContentWhitespace(true);

    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document dDoc = builder.parse("C:/data.xsd");

    Node rootNode = dDoc.getElementsByTagName("xs:schema").item(0);
    System.out.println(rootNode.getNodeName());

    XPath xPath1 = XPathFactory.newInstance().newXPath();
    NamespaceContext nsContext = new NamespaceContext() {
        @Override
        public String getNamespaceURI(String prefix) {
            return "http://www.w3.org/2001/XMLSchema";
        }

        @Override
        public String getPrefix(String namespaceURI) {
            return "xs";
        }

        @Override
        public Iterator getPrefixes(String namespaceURI) {
            Set s = new HashSet();
            s.add("xs");
            return s.iterator();
        }
    };
    xPath1.setNamespaceContext((NamespaceContext) nsContext);
    NodeList nList1 = (NodeList) xPath1.evaluate("//xs:schema", dDoc, XPathConstants.NODESET);
    System.out.println(nList1.item(0).getNodeName());

    NodeList nList2 = (NodeList) xPath1.evaluate("//xs:element", rootNode, XPathConstants.NODESET);
    System.out.println(nList2.item(0).getNodeName());
}

From source file:FindDups.java

public static void main(String[] args) {
    Set<String> s = new HashSet<String>();
    for (String a : args)
        s.add(a);//from   w  w  w  .j  av  a 2s.  com
    System.out.println(s.size() + " distinct words: " + s);
}

From source file:GoogleImages.java

public static void main(String[] args) throws InterruptedException {
    String searchTerm = "s woman"; // term to search for (use spaces to separate terms)
    int offset = 40; // we can only 20 results at a time - use this to offset and get more!
    String fileSize = "50mp"; // specify file size in mexapixels (S/M/L not figured out yet)
    String source = null; // string to save raw HTML source code

    // format spaces in URL to avoid problems
    searchTerm = searchTerm.replaceAll(" ", "%20");

    // get Google image search HTML source code; mostly built from PhyloWidget example:
    // http://code.google.com/p/phylowidget/source/browse/trunk/PhyloWidget/src/org/phylowidget/render/images/ImageSearcher.java
    int offset2 = 0;
    Set urlsss = new HashSet<String>();
    while (offset2 < 600) {
        try {/*w  w w.  java 2 s  . co  m*/
            URL query = new URL("https://www.google.ru/search?start=" + offset2
                    + "&q=angry+woman&newwindow=1&client=opera&hs=bPE&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiAgcKozIfNAhWoHJoKHSb_AUoQ_AUIBygB&biw=1517&bih=731&dpr=0.9#imgrc=G_1tH3YOPcc8KM%3A");
            HttpURLConnection urlc = (HttpURLConnection) query.openConnection(); // start connection...
            urlc.setInstanceFollowRedirects(true);
            urlc.setRequestProperty("User-Agent", "");
            urlc.connect();
            BufferedReader in = new BufferedReader(new InputStreamReader(urlc.getInputStream())); // stream in HTTP source to file
            StringBuffer response = new StringBuffer();
            char[] buffer = new char[1024];
            while (true) {
                int charsRead = in.read(buffer);
                if (charsRead == -1) {
                    break;
                }
                response.append(buffer, 0, charsRead);
            }
            in.close(); // close input stream (also closes network connection)
            source = response.toString();
        } // any problems connecting? let us know
        catch (Exception e) {
            e.printStackTrace();
        }

        // print full source code (for debugging)
        // println(source);
        // extract image URLs only, starting with 'imgurl'
        if (source != null) {
            //                System.out.println(source);
            int c = StringUtils.countMatches(source, "http://www.vmir.su");
            System.out.println(c);
            int index = source.indexOf("src=");
            System.out.println(source.subSequence(index, index + 200));
            while (index >= 0) {
                System.out.println(index);
                index = source.indexOf("src=", index + 1);
                if (index == -1) {
                    break;
                }
                String rr = source.substring(index,
                        index + 200 > source.length() ? source.length() : index + 200);

                if (rr.contains("\"")) {
                    rr = rr.substring(5, rr.indexOf("\"", 5));
                }
                System.out.println(rr);
                urlsss.add(rr);
            }
        }
        offset2 += 20;
        Thread.sleep(1000);
        System.out.println("off set = " + offset2);

    }

    System.out.println(urlsss);
    urlsss.forEach(new Consumer<String>() {

        public void accept(String s) {
            try {
                saveImage(s, "C:\\Users\\Java\\Desktop\\ang\\" + UUID.randomUUID().toString() + ".jpg");
            } catch (IOException ex) {
                Logger.getLogger(GoogleImages.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    });
    //            String[][] m = matchAll(source, "img height=\"\\d+\" src=\"([^\"]+)\"");

    // older regex, no longer working but left for posterity
    // built partially from: http://www.mkyong.com/regular-expressions/how-to-validate-image-file-extension-with-regular-expression
    // String[][] m = matchAll(source, "imgurl=(.*?\\.(?i)(jpg|jpeg|png|gif|bmp|tif|tiff))");    // (?i) means case-insensitive
    //            for (int i = 0; i < m.length; i++) {                                                          // iterate all results of the match
    //                println(i + ":\t" + m[i][1]);                                                         // print (or store them)**
    //            }
}

From source file:com.termmed.sampling.ConceptsWithMoreThanThreeRoleGroups.java

/**
 * The main method./*from ww  w  .  j a  va2  s  . com*/
 *
 * @param args the arguments
 * @throws Exception the exception
 */
public static void main(String[] args) throws Exception {
    System.out.println("Starting...");
    Map<String, Set<String>> groupsMap = new HashMap<String, Set<String>>();
    File relsFile = new File(
            "/Users/alo/Downloads/SnomedCT_RF2Release_INT_20160131-1/Snapshot/Terminology/sct2_Relationship_Snapshot_INT_20160131.txt");
    BufferedReader br2 = new BufferedReader(new FileReader(relsFile));
    String line2;
    int count2 = 0;
    while ((line2 = br2.readLine()) != null) {
        // process the line.
        count2++;
        if (count2 % 10000 == 0) {
            //System.out.println(count2);
        }
        List<String> columns = Arrays.asList(line2.split("\t", -1));
        if (columns.size() >= 6) {
            if (columns.get(2).equals("1") && !columns.get(6).equals("0")) {
                if (!groupsMap.containsKey(columns.get(4))) {
                    groupsMap.put(columns.get(4), new HashSet<String>());
                }
                groupsMap.get(columns.get(4)).add(columns.get(6));
            }
        }
    }
    System.out.println("Relationship groups loaded");
    Gson gson = new Gson();
    System.out.println("Reading JSON 1");
    File crossoverFile1 = new File("/Users/alo/Downloads/crossover_role_to_group.json");
    String contents = FileUtils.readFileToString(crossoverFile1, "utf-8");
    Type collectionType = new TypeToken<Collection<ControlResultLine>>() {
    }.getType();
    List<ControlResultLine> lineObject = gson.fromJson(contents, collectionType);
    Set<String> crossovers1 = new HashSet<String>();
    for (ControlResultLine loopResult : lineObject) {
        crossovers1.add(loopResult.conceptId);
    }
    System.out.println("Crossovers 1 loaded, " + lineObject.size() + " Objects");

    System.out.println("Reading JSON 2");
    File crossoverFile2 = new File("/Users/alo/Downloads/crossover_group_to_group.json");
    String contents2 = FileUtils.readFileToString(crossoverFile2, "utf-8");
    List<ControlResultLine> lineObject2 = gson.fromJson(contents2, collectionType);
    Set<String> crossovers2 = new HashSet<String>();
    for (ControlResultLine loopResult : lineObject2) {
        crossovers2.add(loopResult.conceptId);
    }
    System.out.println("Crossovers 2 loaded, " + lineObject2.size() + " Objects");

    Set<String> foundConcepts = new HashSet<String>();
    int count3 = 0;
    BufferedWriter writer = new BufferedWriter(
            new FileWriter(new File("ConceptsWithMoreThanThreeRoleGroups.csv")));
    ;
    for (String loopConcept : groupsMap.keySet()) {
        if (groupsMap.get(loopConcept).size() > 3) {
            writer.write(loopConcept);
            writer.newLine();
            foundConcepts.add(loopConcept);
            count3++;
        }
    }
    writer.close();
    System.out.println("Found " + foundConcepts.size() + " concepts");

    int countCrossover1 = 0;
    for (String loopConcept : foundConcepts) {
        if (crossovers1.contains(loopConcept)) {
            countCrossover1++;
        }
    }
    System.out.println(countCrossover1 + " are present in crossover_role_to_group");

    int countCrossover2 = 0;
    for (String loopConcept : foundConcepts) {
        if (crossovers2.contains(loopConcept)) {
            countCrossover2++;
        }
    }
    System.out.println(countCrossover2 + " are present in crossover_group_to_group");

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

From source file:com.ignorelist.kassandra.steam.scraper.SharedConfig.java

public static void main(String[] args) throws IOException {
    Set<String> tags = new HashSet<>();
    for (Path p : new PathResolver().findSharedConfig()) {
        SharedConfig sharedConfig = new SharedConfig(p);
        for (Long gameId : sharedConfig.getGameIds()) {
            tags.addAll(sharedConfig.getTags(gameId));
        }//from   ww w . j a va 2s.c o  m
    }
    System.err.println(Joiner.on("\n").join(tags));
}

From source file:com.gargoylesoftware.htmlunit.general.HostExtractor.java

/**
 * The entry point./* w w  w.  j av  a  2 s. c o  m*/
 * @param args optional proxy hostname and port
 * @throws Exception if an error occurs
 */
public static void main(final String[] args) throws Exception {
    final Set<String> set = new HashSet<>();
    try (final WebClient webClient = new WebClient(BrowserVersion.CHROME)) {
        if (args.length > 1) {
            final ProxyConfig proxyConfig = new ProxyConfig(args[0], Integer.parseInt(args[1]));
            proxyConfig.addHostsToProxyBypass("localhost");
            webClient.getOptions().setProxyConfig(proxyConfig);
        }
        fillMDNWebAPI(webClient, set);
        fillMDNJavaScriptGlobalObjects(webClient, set);
        final String testRoot = "src/test/java/";
        ensure(new File(testRoot + HostClassNameTest.class.getName().replace('.', '/') + ".java"), set);
    }
}

From source file:io.fabric8.vertx.maven.plugin.FileFilterMain.java

public static void main(String[] args) {

    Commandline commandline = new Commandline();
    commandline.setExecutable("java");
    commandline.createArg().setValue("io.vertx.core.Launcher");
    commandline.createArg().setValue("--redeploy=target/**/*");

    System.out.println(commandline);/*  ww  w.j  ava 2  s  .  c  o m*/

    File baseDir = new File("/Users/kameshs/git/fabric8io/vertx-maven-plugin/samples/vertx-demo");
    List<String> includes = new ArrayList<>();
    includes.add("src/**/*.java");
    //FileAlterationMonitor monitor  = null;
    try {

        Set<Path> inclDirs = new HashSet<>();

        includes.forEach(s -> {
            try {

                if (s.startsWith("**")) {
                    Path rootPath = Paths.get(baseDir.toString());
                    if (Files.exists(rootPath)) {
                        File[] dirs = rootPath.toFile().listFiles((dir, name) -> dir.isDirectory());
                        Objects.requireNonNull(dirs);
                        Stream.of(dirs).forEach(f -> inclDirs.add(Paths.get(f.toString())));
                    }
                } else if (s.contains("**")) {
                    String root = s.substring(0, s.indexOf("/**"));
                    Path rootPath = Paths.get(baseDir.toString(), root);
                    if (Files.exists(rootPath)) {
                        File[] dirs = rootPath.toFile().listFiles((dir, name) -> dir.isDirectory());
                        Objects.requireNonNull(dirs);
                        Stream.of(dirs).forEach(f -> inclDirs.add(Paths.get(f.toString())));
                    }
                }

                List<Path> dirs = FileUtils.getFileAndDirectoryNames(baseDir, s, null, true, true, true, true)
                        .stream().map(FileUtils::dirname).map(Paths::get)
                        .filter(p -> Files.exists(p) && Files.isDirectory(p)).collect(Collectors.toList());

                inclDirs.addAll(dirs);

            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        FileAlterationMonitor monitor = fileWatcher(inclDirs);

        Runnable monitorTask = () -> {
            try {
                monitor.start();
            } catch (Exception e) {
                e.printStackTrace();
            }
        };

        monitorTask.run();

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:io.reactiverse.vertx.maven.plugin.FileFilterMain.java

public static void main(String[] args) {

    Commandline commandline = new Commandline();
    commandline.setExecutable("java");
    commandline.createArg().setValue("io.vertx.core.Launcher");
    commandline.createArg().setValue("--redeploy=target/**/*");

    System.out.println(commandline);//from w w w. ja  v  a  2s.  c o  m

    File baseDir = new File("/Users/kameshs/git/reactiverse/vertx-maven-plugin/samples/vertx-demo");
    List<String> includes = new ArrayList<>();
    includes.add("src/**/*.java");
    //FileAlterationMonitor monitor  = null;
    try {

        Set<Path> inclDirs = new HashSet<>();

        includes.forEach(s -> {
            try {

                if (s.startsWith("**")) {
                    Path rootPath = Paths.get(baseDir.toString());
                    if (Files.exists(rootPath)) {
                        File[] dirs = rootPath.toFile().listFiles((dir, name) -> dir.isDirectory());
                        Objects.requireNonNull(dirs);
                        Stream.of(dirs).forEach(f -> inclDirs.add(Paths.get(f.toString())));
                    }
                } else if (s.contains("**")) {
                    String root = s.substring(0, s.indexOf("/**"));
                    Path rootPath = Paths.get(baseDir.toString(), root);
                    if (Files.exists(rootPath)) {
                        File[] dirs = rootPath.toFile().listFiles((dir, name) -> dir.isDirectory());
                        Objects.requireNonNull(dirs);
                        Stream.of(dirs).forEach(f -> inclDirs.add(Paths.get(f.toString())));
                    }
                }

                List<Path> dirs = FileUtils.getFileAndDirectoryNames(baseDir, s, null, true, true, true, true)
                        .stream().map(FileUtils::dirname).map(Paths::get)
                        .filter(p -> Files.exists(p) && Files.isDirectory(p)).collect(Collectors.toList());

                inclDirs.addAll(dirs);

            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        FileAlterationMonitor monitor = fileWatcher(inclDirs);

        Runnable monitorTask = () -> {
            try {
                monitor.start();
            } catch (Exception e) {
                e.printStackTrace();
            }
        };

        monitorTask.run();

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:edu.cuhk.hccl.evaluation.EvaluationApp.java

public static void main(String[] args) throws IOException, TasteException {
    File realFile = new File(args[0]);
    File estimateFile = new File(args[1]);

    // Build real-rating map
    Map<String, long[]> realMap = buildRatingMap(realFile);

    // Build estimate-rating map
    Map<String, long[]> estimateMap = buildRatingMap(estimateFile);

    // Compare realMap with estimateMap
    Map<Integer, List<Double>> realList = new HashMap<Integer, List<Double>>();
    Map<Integer, List<Double>> estimateList = new HashMap<Integer, List<Double>>();

    // Use set to store non-duplicate pairs only
    Set<String> noRatingList = new HashSet<String>();

    for (String pair : realMap.keySet()) {
        long[] realRatings = realMap.get(pair);
        long[] estimateRatings = estimateMap.get(pair);

        if (realRatings == null || estimateRatings == null)
            continue;

        for (int i = 0; i < realRatings.length; i++) {
            long real = realRatings[i];
            long estimate = estimateRatings[i];

            // continue if the aspect rating can not be estimated due to incomplete reviews
            if (estimate <= 0) {
                noRatingList.add(pair.replace("@", "\t"));
                continue;
            }/*from  ww  w .  j ava  2 s  .co m*/

            if (real > 0 && estimate > 0) {
                if (!realList.containsKey(i))
                    realList.put(i, new ArrayList<Double>());

                realList.get(i).add((double) real);

                if (!estimateList.containsKey(i))
                    estimateList.put(i, new ArrayList<Double>());

                estimateList.get(i).add((double) estimate);
            }
        }
    }

    System.out.println("[INFO] RMSE, MAE for estimate ratings: ");
    System.out.println("------------------------------");
    System.out.println("Index \t RMSE \t MAE");
    for (int i = 1; i < 6; i++) {
        double rmse = Metric.computeRMSE(realList.get(i), estimateList.get(i));
        double mae = Metric.computeMAE(realList.get(i), estimateList.get(i));

        System.out.printf("%d \t %.3f \t %.3f \n", i, rmse, mae);
    }

    System.out.println("------------------------------");

    if (noRatingList.size() > 0) {
        String noRatingFileName = "evaluation-no-ratings.txt";
        FileUtils.writeLines(new File(noRatingFileName), noRatingList, false);

        System.out.println("[INFO] User-item pairs with no ratings are saved in file: " + noRatingFileName);
    } else {
        System.out.println("[INFO] All user-item pairs have ratings.");
    }
}

From source file:SetStuff.java

public static void main(String[] args) {

    // Create two sets.
    Set s1 = new HashSet();
    s1.add("Ian Darwin");
    s1.add("Bill Dooley");
    s1.add("Jesse James");

    Set s2 = new HashSet();
    s2.add("Ian Darwin");
    s2.add("Doolin' Dalton");

    Set union = new TreeSet(s1);
    union.addAll(s2); // now contains the union

    print("union", union);

    Set intersect = new TreeSet(s1);
    intersect.retainAll(s2);/*from w  w  w .  j a v  a  2  s.c  om*/

    print("intersection", intersect);

}