Example usage for java.util Set add

List of usage examples for java.util Set add

Introduction

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

Prototype

boolean add(E e);

Source Link

Document

Adds the specified element to this set if it is not already present (optional operation).

Usage

From source file:dk.netarkivet.harvester.tools.CreateIndex.java

/**
 * The main method that does the parsing of the commandline, and makes the actual index request.
 *
 * @param args the arguments// w w w . jav  a 2s  . c  om
 */
public static void main(String[] args) {
    Options options = new Options();
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    Option indexType = new Option("t", "type", true, "Type of index");
    Option jobList = new Option("l", "jobids", true, "list of jobids");
    indexType.setRequired(true);
    jobList.setRequired(true);
    options.addOption(indexType);
    options.addOption(jobList);

    try {
        // parse the command line arguments
        cmd = parser.parse(options, args);
    } catch (MissingOptionException e) {
        System.err.println("Some of the required parameters are missing: " + e.getMessage());
        dieWithUsage();
    } catch (ParseException exp) {
        System.err.println("Parsing of parameters failed: " + exp.getMessage());
        dieWithUsage();
    }

    String typeValue = cmd.getOptionValue(INDEXTYPE_OPTION);
    String jobidsValue = cmd.getOptionValue(JOBIDS_OPTION);
    String[] jobidsAsStrings = jobidsValue.split(",");
    Set<Long> jobIDs = new HashSet<Long>();
    for (String idAsString : jobidsAsStrings) {
        jobIDs.add(Long.valueOf(idAsString));
    }

    JobIndexCache cache = null;
    String indexTypeAstring = "";
    if (typeValue.equalsIgnoreCase("CDX")) {
        indexTypeAstring = "CDX";
        cache = IndexClientFactory.getCDXInstance();
    } else if (typeValue.equalsIgnoreCase("DEDUP")) {
        indexTypeAstring = "DEDUP";
        cache = IndexClientFactory.getDedupCrawllogInstance();
    } else if (typeValue.equalsIgnoreCase("CRAWLLOG")) {
        indexTypeAstring = "CRAWLLOG";
        cache = IndexClientFactory.getFullCrawllogInstance();
    } else {
        System.err.println("Unknown indextype '" + typeValue + "' requested.");
        dieWithUsage();
    }

    System.out.println("Creating " + indexTypeAstring + " index for ids: " + jobIDs);
    Index<Set<Long>> index = cache.getIndex(jobIDs);
    JMSConnectionFactory.getInstance().cleanup();
}

From source file:MyObject.java

public static void main(String[] args) {
    Set<MyObject> set = new TreeSet<>(new Comparator<MyObject>() {
        @Override// w w  w  .  j  a  va2 s .c o  m
        public int compare(MyObject left, MyObject right) {
            return left.value - right.value;
        }
    });
    set.add(new MyObject(1));
    set.add(new MyObject(2));
    set.add(new MyObject(3));
    set.add(new MyObject(1)); // '1' is already in set
    System.out.println("size:" + set.size());// print 3
    System.out.println(set.remove(new MyObject(3)));
    System.out.println("size:" + set.size());
}

From source file:ZipCompare.java

public static void main(String[] args) {
    if (args.length != 2) {
        System.out.println("Usage: zipcompare [file1] [file2]");
        System.exit(1);/*from www  .  j  a va  2s  . c om*/
    }

    ZipFile file1;
    try {
        file1 = new ZipFile(args[0]);
    } catch (IOException e) {
        System.out.println("Could not open zip file " + args[0] + ": " + e);
        System.exit(1);
        return;
    }

    ZipFile file2;
    try {
        file2 = new ZipFile(args[1]);
    } catch (IOException e) {
        System.out.println("Could not open zip file " + args[0] + ": " + e);
        System.exit(1);
        return;
    }

    System.out.println("Comparing " + args[0] + " with " + args[1] + ":");

    Set set1 = new LinkedHashSet();
    for (Enumeration e = file1.entries(); e.hasMoreElements();)
        set1.add(((ZipEntry) e.nextElement()).getName());

    Set set2 = new LinkedHashSet();
    for (Enumeration e = file2.entries(); e.hasMoreElements();)
        set2.add(((ZipEntry) e.nextElement()).getName());

    int errcount = 0;
    int filecount = 0;
    for (Iterator i = set1.iterator(); i.hasNext();) {
        String name = (String) i.next();
        if (!set2.contains(name)) {
            System.out.println(name + " not found in " + args[1]);
            errcount += 1;
            continue;
        }
        try {
            set2.remove(name);
            if (!streamsEqual(file1.getInputStream(file1.getEntry(name)),
                    file2.getInputStream(file2.getEntry(name)))) {
                System.out.println(name + " does not match");
                errcount += 1;
                continue;
            }
        } catch (Exception e) {
            System.out.println(name + ": IO Error " + e);
            e.printStackTrace();
            errcount += 1;
            continue;
        }
        filecount += 1;
    }
    for (Iterator i = set2.iterator(); i.hasNext();) {
        String name = (String) i.next();
        System.out.println(name + " not found in " + args[0]);
        errcount += 1;
    }
    System.out.println(filecount + " entries matched");
    if (errcount > 0) {
        System.out.println(errcount + " entries did not match");
        System.exit(1);
    }
    System.exit(0);
}

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

/**
 * The main method./*from   w w w  .j  a  v a2  s  .c  om*/
 *
 * @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:Test.java

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

    Path profile = Paths.get("/user/Admin/.profile");

    PosixFileAttributes attrs = Files.readAttributes(profile, PosixFileAttributes.class);

    Set<PosixFilePermission> posixPermissions = attrs.permissions();
    posixPermissions.clear();//from   w  w w  .ja v a2  s.c om

    String owner = attrs.owner().getName();
    String perms = PosixFilePermissions.toString(posixPermissions);
    System.out.format("%s %s%n", owner, perms);

    posixPermissions.add(OWNER_READ);
    posixPermissions.add(GROUP_READ);
    posixPermissions.add(OWNER_READ);
    posixPermissions.add(OWNER_WRITE);
    Files.setPosixFilePermissions(profile, posixPermissions);

}

From source file:TestCipher.java

public static void main(String args[]) throws Exception {
    Set set = new HashSet();
    Random random = new Random();
    for (int i = 0; i < 10; i++) {
        Point point = new Point(random.nextInt(1000), random.nextInt(2000));
        set.add(point);
    }/*from   ww  w . j  a v a 2  s.  c o m*/
    int last = random.nextInt(5000);

    // Create Key
    byte key[] = password.getBytes();
    DESKeySpec desKeySpec = new DESKeySpec(key);
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
    SecretKey secretKey = keyFactory.generateSecret(desKeySpec);

    // Create Cipher
    Cipher desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
    desCipher.init(Cipher.ENCRYPT_MODE, secretKey);

    // Create stream
    FileOutputStream fos = new FileOutputStream("out.des");
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    CipherOutputStream cos = new CipherOutputStream(bos, desCipher);
    ObjectOutputStream oos = new ObjectOutputStream(cos);

    // Write objects
    oos.writeObject(set);
    oos.writeInt(last);
    oos.flush();
    oos.close();

    // Change cipher mode
    desCipher.init(Cipher.DECRYPT_MODE, secretKey);

    // Create stream
    FileInputStream fis = new FileInputStream("out.des");
    BufferedInputStream bis = new BufferedInputStream(fis);
    CipherInputStream cis = new CipherInputStream(bis, desCipher);
    ObjectInputStream ois = new ObjectInputStream(cis);

    // Read objects
    Set set2 = (Set) ois.readObject();
    int last2 = ois.readInt();
    ois.close();

    // Compare original with what was read back
    int count = 0;
    if (set.equals(set2)) {
        System.out.println("Set1: " + set);
        System.out.println("Set2: " + set2);
        System.out.println("Sets are okay.");
        count++;
    }
    if (last == last2) {
        System.out.println("int1: " + last);
        System.out.println("int2: " + last2);
        System.out.println("ints are okay.");
        count++;
    }
    if (count != 2) {
        System.out.println("Problem during encryption/decryption");
    }
}

From source file:SetTest.java

public static void main(String[] args) {
    Set<String> words = new HashSet<String>(); // HashSet implements Set
    long totalTime = 0;

    Scanner in = new Scanner(System.in);
    while (in.hasNext()) {
        String word = in.next();//w w  w  .j  a  v  a  2s  .  com
        long callTime = System.currentTimeMillis();
        words.add(word);
        callTime = System.currentTimeMillis() - callTime;
        totalTime += callTime;
    }

    Iterator<String> iter = words.iterator();
    for (int i = 1; i <= 20 && iter.hasNext(); i++)
        System.out.println(iter.next());
    System.out.println(". . .");
    System.out.println(words.size() + " distinct words. " + totalTime + " milliseconds.");
}

From source file:de.zib.vold.userInterface.ABI.java

public static void main(String[] args) {
    ABI abi = new ABI();

    while (true) {
        try {/*  ww  w. j  a v  a 2 s . c om*/
            InputStreamReader isr = new InputStreamReader(System.in);
            BufferedReader br = new BufferedReader(isr);

            System.out.print("#: ");

            String s = br.readLine();
            if (null == s)
                break;

            String[] a = s.split("\\s+");

            if (a.length < 1) {
                System.out.println("ERROR: The following commands are valid:");
                System.out.println("ERROR: insert <source> <scope> <type> <keyname> {<value> }*");
                System.out.println("ERROR: lookup <scope> <type> <keyname>");
                System.out.println("ERROR: exit");

                continue;
            } else if (a[0].equals("lookup") || a[0].equals("l")) {
                if (a.length < 4) {
                    System.out.println("ERROR: Syntax for lookup is:");
                    System.out.println("ERROR: lookup <scope> <type> <keyname>");

                    continue;
                }

                Map<Key, Set<String>> result;
                try {
                    result = abi.frontend.lookup(new Key(a[1], a[2], a[3]));
                } catch (VoldException e) {
                    System.out.println(
                            "An internal error occured: " + e.getClass().getName() + ": " + e.getMessage());
                    continue;
                }

                for (Map.Entry<Key, Set<String>> entry : result.entrySet()) {
                    Key k = entry.getKey();
                    System.out.println("+Found ('" + k.get_scope() + "', '" + k.get_type() + "', '"
                            + k.get_keyname() + "')");

                    for (String v : entry.getValue()) {
                        System.out.println("-" + v);
                    }
                }
            } else if (a[0].equals("insert") || a[0].equals("i")) {
                if (a.length < 5) {
                    System.out.println("ERROR: Syntax for insert is:");
                    System.out.println("ERROR: insert <source> <scope> <type> <keyname> {<value> }*");

                    continue;
                }

                Key k = new Key(a[2], a[3], a[4]);

                Set<String> values = new HashSet<String>();
                for (int i = 5; i < a.length; ++i) {
                    values.add(a[i]);
                }

                try {
                    abi.frontend.insert(a[1], k, values, DateTime.now().getMillis());
                } catch (VoldException e) {
                    System.out.println(
                            "An internal error occured: " + e.getClass().getName() + ": " + e.getMessage());
                    continue;
                }
            } else if (a[0].equals("exit") || a[0].equals("x")) {
                break;
            } else {
                System.out.println("ERROR: Unknown command!");
                System.out.println("ERROR: The following commands are valid:");
                System.out.println("ERROR: insert <source> <scope> <type> <keyname> {<value> }*");
                System.out.println("ERROR: lookup <scope> <type> <keyname>");
                System.out.println("ERROR: exit");
            }

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

    System.exit(0);
}

From source file:com.mfalaize.zipdiff.Main.java

/**
 * The command line interface to zipdiff utility
 *
 * @param args The command line parameters
 *///from  w  w w.  j  ava 2 s . c  om
public static void main(String[] args) {
    CommandLineParser parser = new DefaultParser();

    try {
        CommandLine line = parser.parse(options, args);

        String filename1;
        String filename2;

        filename1 = line.getOptionValue(OPTION_FILE1);
        filename2 = line.getOptionValue(OPTION_FILE2);

        File f1 = new File(filename1);
        File f2 = new File(filename2);

        checkFile(f1);
        checkFile(f2);

        System.out.println("File 1 = " + f1);
        System.out.println("File 2 = " + f2);

        DifferenceCalculator calc = new DifferenceCalculator(f1, f2);

        String regularExpression;

        // todo - calc.setFilenamesToIgnore();

        if (line.hasOption(OPTION_COMPARE_CRC_VALUES)) {
            calc.setCompareCRCValues(true);
        } else {
            calc.setCompareCRCValues(false);
        }

        if (line.hasOption(OPTION_IGNORE_CVS_FILES)) {
            calc.setIgnoreCVSFiles(true);
        } else {
            calc.setIgnoreCVSFiles(false);
        }

        if (line.hasOption(OPTION_COMPARE_TIMESTAMPS)) {
            calc.setIgnoreTimestamps(false);
        } else {
            calc.setIgnoreTimestamps(true);
        }

        if (line.hasOption(OPTION_REGEX)) {
            regularExpression = line.getOptionValue(OPTION_REGEX);
            Set<String> regexSet = new HashSet<String>();
            regexSet.add(regularExpression);

            calc.setFilenameRegexToIgnore(regexSet);
        }

        boolean exitWithErrorOnDiff = false;
        if (line.hasOption(OPTION_EXIT_WITH_ERROR_ON_DIFF)) {
            exitWithErrorOnDiff = true;
        }

        Differences d = calc.getDifferences();

        if (line.hasOption(OPTION_OUTPUT_FILE)) {
            String outputFilename = line.getOptionValue(OPTION_OUTPUT_FILE);
            writeOutputFile(outputFilename, d);
        }

        if (d.hasDifferences()) {
            if (line.hasOption(OPTION_VERBOSE)) {
                System.out.println(d);
                System.out.println(d.getFilename1() + " and " + d.getFilename2() + " are different.");
            }
            if (exitWithErrorOnDiff) {
                System.exit(EXITCODE_DIFF);
            }
        } else {
            System.out.println("No differences found.");
        }
    } catch (ParseException pex) {
        System.err.println(pex.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("Main [options] ", options);
        System.exit(EXITCODE_ERROR);
    } catch (Exception ex) {
        ex.printStackTrace();
        System.exit(EXITCODE_ERROR);
    }

}

From source file:cc.twittertools.search.api.RunQueriesThrift.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    Options options = new Options();

    options.addOption(OptionBuilder.withArgName("string").hasArg().withDescription("host").create(HOST_OPTION));
    options.addOption(OptionBuilder.withArgName("port").hasArg().withDescription("port").create(PORT_OPTION));
    options.addOption(OptionBuilder.withArgName("file").hasArg()
            .withDescription("file containing topics in TREC format").create(QUERIES_OPTION));
    options.addOption(OptionBuilder.withArgName("num").hasArg().withDescription("number of results to return")
            .create(NUM_RESULTS_OPTION));
    options.addOption(//from   w  w  w  .j  a  va2  s .  c o m
            OptionBuilder.withArgName("string").hasArg().withDescription("group id").create(GROUP_OPTION));
    options.addOption(
            OptionBuilder.withArgName("string").hasArg().withDescription("access token").create(TOKEN_OPTION));
    options.addOption(
            OptionBuilder.withArgName("string").hasArg().withDescription("runtag").create(RUNTAG_OPTION));
    options.addOption(new Option(VERBOSE_OPTION, "print out complete document"));

    CommandLine cmdline = null;
    CommandLineParser parser = new GnuParser();
    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (!cmdline.hasOption(HOST_OPTION) || !cmdline.hasOption(PORT_OPTION)
            || !cmdline.hasOption(QUERIES_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(RunQueriesThrift.class.getName(), options);
        System.exit(-1);
    }

    String queryFile = cmdline.getOptionValue(QUERIES_OPTION);
    if (!new File(queryFile).exists()) {
        System.err.println("Error: " + queryFile + " doesn't exist!");
        System.exit(-1);
    }

    String runtag = cmdline.hasOption(RUNTAG_OPTION) ? cmdline.getOptionValue(RUNTAG_OPTION) : DEFAULT_RUNTAG;

    TrecTopicSet topicsFile = TrecTopicSet.fromFile(new File(queryFile));

    int numResults = 1000;
    try {
        if (cmdline.hasOption(NUM_RESULTS_OPTION)) {
            numResults = Integer.parseInt(cmdline.getOptionValue(NUM_RESULTS_OPTION));
        }
    } catch (NumberFormatException e) {
        System.err.println("Invalid " + NUM_RESULTS_OPTION + ": " + cmdline.getOptionValue(NUM_RESULTS_OPTION));
        System.exit(-1);
    }

    String group = cmdline.hasOption(GROUP_OPTION) ? cmdline.getOptionValue(GROUP_OPTION) : null;
    String token = cmdline.hasOption(TOKEN_OPTION) ? cmdline.getOptionValue(TOKEN_OPTION) : null;

    boolean verbose = cmdline.hasOption(VERBOSE_OPTION);

    PrintStream out = new PrintStream(System.out, true, "UTF-8");

    TrecSearchThriftClient client = new TrecSearchThriftClient(cmdline.getOptionValue(HOST_OPTION),
            Integer.parseInt(cmdline.getOptionValue(PORT_OPTION)), group, token);

    for (cc.twittertools.search.TrecTopic query : topicsFile) {
        List<TResult> results = client.search(query.getQuery(), query.getQueryTweetTime(), numResults);
        int i = 1;
        Set<Long> tweetIds = new HashSet<Long>();
        for (TResult result : results) {
            if (!tweetIds.contains(result.id)) {
                tweetIds.add(result.id);
                out.println(
                        String.format("%s Q0 %d %d %f %s", query.getId(), result.id, i, result.rsv, runtag));
                if (verbose) {
                    out.println("# " + result.toString().replaceAll("[\\n\\r]+", " "));
                }
                i++;
            }
        }
    }
    out.close();
}