Example usage for java.util Set remove

List of usage examples for java.util Set remove

Introduction

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

Prototype

boolean remove(Object o);

Source Link

Document

Removes the specified element from this set if it is present (optional operation).

Usage

From source file:TreeSetExample.java

public static void main(String[] args) {
    // Create a new TreeSet
    Set<Integer> set = new TreeSet<Integer>();

    // Add Items to the TreeSet
    set.add(new Integer(1));
    set.add(new Integer(2));
    set.add(new Integer(3));
    set.add(new Integer(4));
    set.add(new Integer(5));
    set.add(new Integer(6));
    set.add(new Integer(7));
    set.add(new Integer(8));
    set.add(new Integer(9));
    set.add(new Integer(10));

    // Use iterator to display the vsetes
    System.out.println("TreeSet Before: ");
    for (Iterator i = set.iterator(); i.hasNext();) {
        Integer integer = (Integer) i.next();
        System.out.println(integer);
    }// w ww.  java  2 s.c o m

    // Remove the integer 6
    System.out.println("\nRemove Integer 6");
    set.remove(new Integer(6));

    // Use iterator to display the vsetes
    System.out.println("\nTreeSet After: ");
    for (Iterator i = set.iterator(); i.hasNext();) {
        Integer integer = (Integer) i.next();
        System.out.println(integer);
    }

}

From source file:de.uni_rostock.goodod.checker.CheckerApp.java

public static void main(String[] args) throws OWLOntologyCreationException {
    config = Configuration.getConfiguration(args);
    String bioTopVariantA = "biotoplite_group_A_TEST.owl";
    String bioTopVariantB = "biotoplite_group_B_TEST.owl";
    String repoRoot = config.getString("repositoryRoot");
    File commonBioTopF = new File(repoRoot + File.separator + config.getString("bioTopLiteSource"));

    String groupAFile = repoRoot + File.separator + "Results" + File.separator + "GruppeA" + File.separator
            + bioTopVariantA;/*from  www.j ava 2 s  .co  m*/
    String groupBFile = repoRoot + File.separator + "Results" + File.separator + "GruppeB" + File.separator
            + bioTopVariantB;
    String testFile = config.getString("testDescription");
    IRI bioTopIRI = IRI.create("http://purl.org/biotop/biotoplite.owl");
    SimpleIRIMapper bioTopLiteMapper = new SimpleIRIMapper(bioTopIRI, IRI.create(commonBioTopF));
    SimpleIRIMapper variantMapperA = new SimpleIRIMapper(
            IRI.create("http://purl.org/biotop/biotoplite_group_A_TEST.owl"), IRI.create(new File(groupAFile)));
    SimpleIRIMapper variantMapperB = new SimpleIRIMapper(
            IRI.create("http://purl.org/biotop/biotoplite_group_B_TEST.owl"), IRI.create(new File(groupBFile)));
    //logger.info("Loading ontology " + testFile + ".");
    OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
    manager.addIRIMapper(variantMapperA);
    manager.addIRIMapper(variantMapperB);
    manager.addIRIMapper(bioTopLiteMapper);
    FileDocumentSource source = new FileDocumentSource(new File(testFile));
    OWLOntology ontology = null;
    try {
        ontology = manager.loadOntologyFromOntologyDocument(source);
    } catch (Throwable e) {
        logger.fatal("Loading failed", e);
        System.exit(1);
    }

    org.semanticweb.HermiT.Configuration reasonerConfig = new org.semanticweb.HermiT.Configuration();
    reasonerConfig.throwInconsistentOntologyException = false;
    //ReasonerProgressMonitor monitor = new ConsoleProgressMonitor();
    reasonerConfig.existentialStrategyType = ExistentialStrategyType.INDIVIDUAL_REUSE;
    //reasonerConfig.reasonerProgressMonitor = monitor;
    reasonerConfig.tableauMonitorType = TableauMonitorType.NONE;
    //reasonerConfig.individualTaskTimeout = 10000;
    Reasoner reasoner = new Reasoner(reasonerConfig, ontology);
    reasoner.classifyClasses();
    Set<OWLClass> before = reasoner.getUnsatisfiableClasses()
            .getEntitiesMinus(manager.getOWLDataFactory().getOWLNothing());
    //logger.info("Found " + before.size() + " inconsistent classes before import change.");
    logger.debug(before);

    reasoner.dispose();
    reasoner = null;
    manager.removeOntology(ontology);
    ontology = null;

    Map<IRI, IRI> importMap = new HashMap<IRI, IRI>();

    OWLOntologyLoaderConfiguration interimConfig = new OWLOntologyLoaderConfiguration();
    for (String str : config.getStringArray("ignoredImports")) {
        IRI ignoredIRI = IRI.create(str);
        importMap.put(ignoredIRI, bioTopIRI);

        interimConfig = interimConfig.addIgnoredImport(ignoredIRI);
    }

    interimConfig = interimConfig.setMissingImportHandlingStrategy(MissingImportHandlingStrategy.SILENT);
    try {
        ontology = manager.loadOntologyFromOntologyDocument(source, interimConfig);
    } catch (Throwable e) {
        logger.fatal("Loading failed", e);
        System.exit(1);
    }
    BasicImportingNormalizerFactory n = new BasicImportingNormalizerFactory(importMap, interimConfig);

    n.normalize(ontology);

    reasoner = new Reasoner(reasonerConfig, ontology);
    reasoner.classifyClasses();
    Set<OWLClass> after = reasoner.getUnsatisfiableClasses()
            .getEntitiesMinus(manager.getOWLDataFactory().getOWLNothing());

    //logger.info("Found " + after.size() + " inconsistent classes after import change.");
    logger.debug(after);

    /*
     * We need some tidying afterwards. The after set can contain
     * inconsistent classes that are inconsistent only because in the new
     * import, they are subclasses of a class that was already inconsistent before.
     * Hence we remove them from the after set.  
     */
    for (OWLClass c : before) {
        Set<OWLClass> subclasses = SubClassCollector.collect(c, manager.getImportsClosure(ontology));
        for (OWLClass subC : subclasses) {
            if ((true == after.contains(subC)) && (false == before.contains(subC))) {
                after.remove(subC);
            }
        }
    }
    int difference = before.size() - after.size();

    if (0 == difference) {
        logger.info(testFile + ": OK");
    } else {
        logger.warn(testFile + ": Import change is not neutral to inconsistencies (" + before.size() + '/'
                + after.size() + ")");
    }
}

From source file:de.clusteval.serverclient.BackendClient.java

/**
 * @param args/*  w ww .  j a v  a2s  .c om*/
 *            Command line parameters for the backend client (see
 *            {@link #params}).
 * @throws IOException
 */
@SuppressWarnings("unused")
public static void main(String[] args) throws IOException {
    try {
        CommandLine params = parseParams(args, false);

        if (params.hasOption("help")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("clustevalClient", clientCLIOptions);
            System.exit(0);
        }

        if (params.hasOption("version")) {
            System.out.println(VERSION);
            System.exit(0);
        }

        initLogging(params);

        Logger log = LoggerFactory.getLogger(BackendClient.class);

        System.out.println("Starting clusteval client");
        System.out.println(VERSION);
        System.out.println("=========================");

        // if command line arguments (except connection parameters) are
        // passed, we do not start a console
        Set<String> paramKeys = new HashSet<String>();
        @SuppressWarnings("unchecked")
        Iterator<Option> it = params.iterator();
        while (it.hasNext()) {
            paramKeys.add(it.next().getOpt());
        }

        paramKeys.remove("ip");
        paramKeys.remove("port");
        paramKeys.remove("clientId");
        if (paramKeys.size() > 0) {
            try {
                new BackendClient(args);
            } catch (Exception e) {
            }
        } else {
            String clientId;
            if (params.hasOption("clientId"))
                clientId = params.getOptionValue("clientId");
            else
                // parse args because of possible connection parameters
                clientId = new BackendClient(args).clientId;

            reader = new ConsoleReader();

            List<Completer> completers = new LinkedList<Completer>();
            completers.add(new BackendClientCompleter(clientId, args));

            String ip = params.hasOption("ip") ? params.getOptionValue("ip") : "localhost";
            String port = params.hasOption("port") ? params.getOptionValue("port") : "1099";

            setDefaultPromptAndCompleter(ip, port, completers);

            String line;

            while ((line = reader.readLine()) != null) {

                if (line.equalsIgnoreCase("quit") || line.equalsIgnoreCase("exit")) {
                    break;
                }

                boolean connectException = false;
                do {
                    try {
                        new BackendClient(
                                ArraysExt.merge(args, ("-clientId " + clientId + " -" + line).split(" ")));
                        connectException = false;
                    } catch (ConnectException e) {
                        e.printStackTrace();
                        connectException = true;
                    } catch (Exception e) {
                        log.warn(e.getMessage());
                    }
                    Thread.sleep(1000);
                } while (connectException);
                // }
            }
        }
    } catch (ParseException e) {
        System.err.println("Parsing failed.  Reason: " + e.getMessage());

        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("clustevalClient",
                "Invoking this client without any parameters will open a shell with tab-completion.",
                clientCLIOptions, "", true);
    } catch (Throwable t) {
        // t.printStackTrace();
    }
}

From source file:edu.jhu.hlt.concrete.gigaword.expt.ConvertGigawordDocuments.java

/**
 * @param args//from  w w w  . j  a  va  2  s . co  m
 */
public static void main(String... args) {
    Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {

        @Override
        public void uncaughtException(Thread t, Throwable e) {
            logger.error("Thread {} caught unhandled exception.", t.getName());
            logger.error("Unhandled exception.", e);
        }
    });

    if (args.length != 2) {
        logger.info("Usage: {} {} {}", GigawordConcreteConverter.class.getName(), "path/to/expt/file",
                "path/to/out/folder");
        System.exit(1);
    }

    String exptPathStr = args[0];
    String outPathStr = args[1];

    // Verify path points to something.
    Path exptPath = Paths.get(exptPathStr);
    if (!Files.exists(exptPath)) {
        logger.error("File: {} does not exist. Re-run with the correct path to "
                + " the experiment 2 column file. See README.md.");
        System.exit(1);
    }

    logger.info("Experiment map located at: {}", exptPathStr);

    // Create output dir if not yet created.
    Path outPath = Paths.get(outPathStr);
    if (!Files.exists(outPath)) {
        logger.info("Creating directory: {}", outPath.toString());
        try {
            Files.createDirectories(outPath);
        } catch (IOException e) {
            logger.error("Caught an IOException when creating output dir.", e);
            System.exit(1);
        }
    }

    logger.info("Output directory located at: {}", outPathStr);

    // Read in expt map. See README.md.
    Map<String, Set<String>> exptMap = null;
    try (Reader r = ExperimentUtils.createReader(exptPath); BufferedReader br = new BufferedReader(r)) {
        exptMap = ExperimentUtils.createFilenameToIdMap(br);
    } catch (IOException e) {
        logger.error("Caught an IOException when creating expt map.", e);
        System.exit(1);
    }

    // Start a timer.
    logger.info("Gigaword -> Concrete beginning.");
    StopWatch sw = new StopWatch();
    sw.start();
    // Iterate over expt map.
    exptMap.entrySet()
            // .parallelStream()
            .forEach(p -> {
                final String pathStr = p.getKey();
                final Set<String> ids = p.getValue();
                final Path lp = Paths.get(pathStr);
                logger.info("Converting path: {}", pathStr);

                // Get the file name and immediate folder it is under.
                int nElements = lp.getNameCount();
                Path fileName = lp.getName(nElements - 1);
                Path subFolder = lp.getName(nElements - 2);
                String newFnStr = fileName.toString().split("\\.")[0] + ".tar";

                // Mirror folders in output dir.
                Path localOutFolder = outPath.resolve(subFolder);
                Path localOutPath = localOutFolder.resolve(newFnStr);

                // Create output subfolders.
                if (!Files.exists(localOutFolder) && !Files.isDirectory(localOutFolder)) {
                    logger.info("Creating out file: {}", localOutFolder.toString());
                    try {
                        Files.createDirectories(localOutFolder);
                    } catch (IOException e) {
                        throw new RuntimeException("Caught an IOException when creating output dir.", e);
                    }
                }

                // Iterate over communications.
                Iterator<Communication> citer;
                try (OutputStream os = Files.newOutputStream(localOutPath);
                        BufferedOutputStream bos = new BufferedOutputStream(os);
                        Archiver archiver = new TarArchiver(bos);) {
                    citer = new ConcreteGigawordDocumentFactory().iterator(lp);
                    while (citer.hasNext()) {
                        Communication c = citer.next();
                        String cId = c.getId();

                        // Document ID must be in the set. Remove.
                        boolean wasInSet = ids.remove(cId);
                        if (!wasInSet) {
                            // Some IDs are duplicated in Gigaword.
                            // See ERRATA.
                            logger.debug(
                                    "ID: {} was parsed from path: {}, but was not in the experiment map. Attempting to remove dupe.",
                                    cId, pathStr);

                            // Attempt to create a duplicate id (append .duplicate to the id).
                            // Then, try to remove again.
                            String newId = RepairDuplicateIDs.repairDuplicate(cId);
                            boolean dupeRemoved = ids.remove(newId);
                            // There are not nested duplicates, so this should never fire.
                            if (!dupeRemoved) {
                                logger.info("Failed to remove dupe.");
                                return;
                            } else
                                // Modify the communication ID to the unique version.
                                c.setId(newId);
                        }

                        archiver.addEntry(new ArchivableCommunication(c));
                    }

                    logger.info("Finished path: {}", pathStr);
                } catch (ConcreteException ex) {
                    logger.error("Caught ConcreteException during Concrete mapping.", ex);
                    logger.error("Path: {}", pathStr);
                } catch (IOException e) {
                    logger.error("Error archiving communications.", e);
                    logger.error("Path: {}", localOutPath.toString());
                }
            });

    sw.stop();
    logger.info("Finished.");
    Minutes m = new Duration(sw.getTime()).toStandardMinutes();
    logger.info("Runtime: Approximately {} minutes.", m.getMinutes());
}

From source file:Main.java

/**
 * Remove the value from collection coll and return a new collection.
 *///  w w w  . j  ava 2s  .  c  o  m
public static <T> Set<T> remove(Collection<T> coll, T value) {
    Set<T> copy = new HashSet<T>(coll);
    copy.remove(value);
    return copy;
}

From source file:Test.java

private static void removePermission(Path path, PosixFilePermission permission) throws Exception {
    System.out.println("\nRemoving permission for " + path.getFileName());
    PosixFileAttributeView view = Files.getFileAttributeView(path, PosixFileAttributeView.class);

    PosixFileAttributes attributes = view.readAttributes();

    Set<PosixFilePermission> permissions = attributes.permissions();
    permissions.remove(permission);

    view.setPermissions(permissions);//ww w .j ava  2s  .c om
    System.out.println();
}

From source file:Main.java

/**
 * Removes the value from the set of values mapped by key. If this value was the last value in the set of values
 * mapped by key, the complete key/values entry is removed.
 * /*  w ww.  j  av  a 2s . c o m*/
 * @param key
 *            The key for which to remove a value.
 * @param value
 *            The value for which to remove the key.
 * @param map
 *            The object that maps the key to a set of values, on which the operation should occur.
 */
public static <K, V> void deleteAndRemove(final K key, final V value, final Map<K, Set<V>> map) {
    if (key == null) {
        throw new IllegalArgumentException("Argument 'key' cannot be null.");
    }
    if (value == null) {
        throw new IllegalArgumentException("Argument 'value' cannot be null.");
    }
    if (map == null) {
        throw new IllegalArgumentException("Argument 'map' cannot be null.");
    }

    if (map.isEmpty() || !map.containsKey(key)) {
        return;
    }

    final Set<V> values = map.get(key);
    values.remove(value);

    if (values.isEmpty()) {
        map.remove(key);
    }
}

From source file:Main.java

public static void logOutUser(Context context, String userId) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    Set<String> currentUsers = prefs.getStringSet(LOGGED_IN_USER_PREFERENCE_KEY, new HashSet<>());
    currentUsers.remove(userId);
    PreferenceManager.getDefaultSharedPreferences(context).edit()
            .putStringSet(LOGGED_IN_USER_PREFERENCE_KEY, currentUsers).commit();
}

From source file:Main.java

public static <T, V extends T> Set<T> removeObjectSet(Set<T> set, V o) {
    if (set == null) {
        set = new HashSet<T>(1);
    }/*from  w w w  .  ja v a 2s.com*/
    set.remove(o);
    return set;
}

From source file:es.emergya.ui.base.plugins.PluginType.java

public static Set<String> getAll() {
    Set<String> res = ptc.keySet();
    res.remove(UNKNOWN);
    return res;//ww  w.jav a 2 s  . com
}