Example usage for java.util Collections singleton

List of usage examples for java.util Collections singleton

Introduction

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

Prototype

public static <T> Set<T> singleton(T o) 

Source Link

Document

Returns an immutable set containing only the specified object.

Usage

From source file:MainClass.java

public static void main(String[] a) {
    System.out.println(Collections.singletonList("a"));
    System.out.println(Collections.singleton("a"));
    System.out.println(Collections.singletonMap("a", "b"));

}

From source file:MainClass.java

public static void main(String args[]) {
    String init[] = { "One", "Two", "Three", "One", "Two", "Three" };
    List list1 = new ArrayList(Arrays.asList(init));
    List list2 = new ArrayList(Arrays.asList(init));
    list1.remove("One");
    System.out.println(list1);//from   www  .j  av a2  s  .co m
    list2.removeAll(Collections.singleton("One"));
    System.out.println(list2);
}

From source file:Main.java

public static void main(String[] args) {
    String givenstring = "this is a test this is a another test";
    String[] words = givenstring.split(" ");

    ArrayList<String> arr = new ArrayList<String>();
    for (int i = 0; i < words.length; i++) {
        arr.add(words[i]);/*from  w  ww . j  a va 2  s. c om*/
    }
    while (arr.size() != 0) {
        String word = arr.get(0);
        int frequency = Collections.frequency(arr, word);
        arr.removeAll(Collections.singleton(word));
        System.out.println(word + frequency);
    }
}

From source file:Main.java

public static void main(String args[]) {
    String init[] = { "One", "Two", "Three", "One", "Two", "Three" };

    // create two lists
    List<String> list1 = new ArrayList<String>(Arrays.asList(init));
    List<String> list2 = new ArrayList<String>(Arrays.asList(init));

    // remove from list1
    list1.remove("One");
    System.out.println("List1 value: " + list1);

    // remove from list2 using singleton
    list2.removeAll(Collections.singleton("One"));
    System.out.println("The SingletonList is :" + list2);
}

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    List mylist = new ArrayList();
    FileInputStream in = new FileInputStream(args[0]);
    Certificate c = cf.generateCertificate(in);
    mylist.add(c);//w  w w. j av a2s. c  o m

    CertPath cp = cf.generateCertPath(mylist);

    Certificate trust = cf.generateCertificate(in);
    TrustAnchor anchor = new TrustAnchor((X509Certificate) trust, null);
    PKIXParameters params = new PKIXParameters(Collections.singleton(anchor));
    params.setRevocationEnabled(false);
    CertPathValidator cpv = CertPathValidator.getInstance("PKIX");
    PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult) cpv.validate(cp, params);
    System.out.println(result);
}

From source file:io.kodokojo.monitor.Launcher.java

public static void main(String[] args) {

    Injector propertyInjector = Guice.createInjector(new CommonsPropertyModule(args), new PropertyModule());
    MicroServiceConfig microServiceConfig = propertyInjector.getInstance(MicroServiceConfig.class);
    LOGGER.info("Starting Kodo Kojo {}.", microServiceConfig.name());
    Injector commonsServicesInjector = propertyInjector.createChildInjector(new UtilityServiceModule(),
            new EventBusModule(), new DatabaseModule(), new SecurityModule(), new CommonsHealthCheckModule());

    Injector marathonInjector = null;//from  w w  w.  ja va  2 s  .c  o m
    OrchestratorConfig orchestratorConfig = propertyInjector.getInstance(OrchestratorConfig.class);
    if (MOCK.equals(orchestratorConfig.orchestrator())) {
        marathonInjector = commonsServicesInjector.createChildInjector(new AbstractModule() {
            @Override
            protected void configure() {
                //
            }

            @Singleton
            @Provides
            BrickStateLookup provideBrickStateLookup() {
                return new BrickStateLookup() {

                    private int cpt = 0;

                    @Override
                    public Set<BrickStateEvent> lookup() {
                        return Collections.singleton(generateBrickStateEvent());
                    }

                    public BrickStateEvent generateBrickStateEvent() {
                        BrickStateEvent.State[] states = BrickStateEvent.State.values();
                        int index = RandomUtils.nextInt(states.length);
                        BrickStateEvent.State state = states[index];

                        return new BrickStateEvent("1234", "build-A", BrickType.CI.name(), "jenkins", state,
                                "1.65Z3.1");
                    }
                };
            }
        });
    } else {
        marathonInjector = commonsServicesInjector.createChildInjector(new AbstractModule() {
            @Override
            protected void configure() {
                //
            }

            @Singleton
            @Provides
            BrickStateLookup provideBrickStateLookup(MarathonConfig marathonConfig,
                    ProjectFetcher projectFectcher, BrickFactory brickFactory, BrickUrlFactory brickUrlFactory,
                    OkHttpClient httpClient) {
                return new MarathonBrickStateLookup(marathonConfig, projectFectcher, brickFactory,
                        brickUrlFactory, httpClient);
            }

        });
    }

    Injector servicesInjector = marathonInjector.createChildInjector(new ServiceModule());

    ApplicationLifeCycleManager applicationLifeCycleManager = servicesInjector
            .getInstance(ApplicationLifeCycleManager.class);
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            super.run();
            LOGGER.info("Stopping services.");
            applicationLifeCycleManager.stop();
            LOGGER.info("All services stopped.");
        }
    });

    EventBus eventBus = servicesInjector.getInstance(EventBus.class);
    eventBus.connect();
    //  Init repository.
    BrickStateLookup brickStateLookup = servicesInjector.getInstance(BrickStateLookup.class);
    BrickStateEventRepository repository = servicesInjector.getInstance(BrickStateEventRepository.class);
    Set<BrickStateEvent> brickStateEvents = brickStateLookup.lookup();
    repository.compareAndUpdate(brickStateEvents);

    HttpHealthCheckEndpoint httpHealthCheckEndpoint = servicesInjector
            .getInstance(HttpHealthCheckEndpoint.class);
    httpHealthCheckEndpoint.start();

    ActorSystem actorSystem = servicesInjector.getInstance(ActorSystem.class);
    ActorRef actorRef = servicesInjector.getInstance(ActorRef.class);
    actorSystem.scheduler().schedule(Duration.Zero(), Duration.create(1, TimeUnit.MINUTES), actorRef, "Tick",
            actorSystem.dispatcher(), ActorRef.noSender());
    LOGGER.info("Kodo Kojo {} started.", microServiceConfig.name());

}

From source file:joshelser.as2015.ingester.CategoryUpdater.java

public static void main(String[] args) throws Exception {
    JCommander commander = new JCommander();
    final Opts options = new Opts();
    commander.addObject(options);//w  w w . j a  v  a  2  s .  c  o m

    commander.setProgramName("Query");
    try {
        commander.parse(args);
    } catch (ParameterException ex) {
        commander.usage();
        System.err.println(ex.getMessage());
        System.exit(1);
    }

    ClientConfiguration conf = ClientConfiguration.loadDefault();
    if (null != options.clientConfFile) {
        conf = new ClientConfiguration(new PropertiesConfiguration(options.clientConfFile));
    }
    conf.withInstance(options.instanceName).withZkHosts(options.zookeepers);

    ZooKeeperInstance inst = new ZooKeeperInstance(conf);
    Connector conn = inst.getConnector(options.user, new PasswordToken(options.password));

    BatchScanner bs = conn.createBatchScanner(options.table, Authorizations.EMPTY, 16);
    BatchWriter bw = conn.createBatchWriter(options.table, new BatchWriterConfig());
    try {
        bs.setRanges(Collections.singleton(new Range()));
        final Text categoryText = new Text("category");
        bs.fetchColumnFamily(categoryText);

        final Text categoryName = new Text("name");
        final Text row = new Text();
        for (Entry<Key, Value> entry : bs) {
            entry.getKey().getRow(row);
            Mutation m = new Mutation(row);
            m.put(categoryText, categoryName, entry.getValue());

            bw.addMutation(m);
        }
    } finally {
        bs.close();
        bw.close();
    }
}

From source file:joshelser.as2015.query.Query.java

public static void main(String[] args) throws Exception {
    JCommander commander = new JCommander();
    final Opts options = new Opts();
    commander.addObject(options);/*from ww  w. jav  a2s . co m*/

    commander.setProgramName("Query");
    try {
        commander.parse(args);
    } catch (ParameterException ex) {
        commander.usage();
        System.err.println(ex.getMessage());
        System.exit(1);
    }

    ClientConfiguration conf = ClientConfiguration.loadDefault();
    if (null != options.clientConfFile) {
        conf = new ClientConfiguration(new PropertiesConfiguration(options.clientConfFile));
    }
    conf.withInstance(options.instanceName).withZkHosts(options.zookeepers);

    ZooKeeperInstance inst = new ZooKeeperInstance(conf);
    Connector conn = inst.getConnector(options.user, new PasswordToken(options.password));

    BatchScanner bs = conn.createBatchScanner(options.table, Authorizations.EMPTY, 16);
    try {
        bs.setRanges(Collections.singleton(new Range()));
        final Text categoryText = new Text("category");
        bs.fetchColumn(categoryText, new Text("name"));
        bs.fetchColumn(new Text("review"), new Text("score"));
        bs.fetchColumn(new Text("review"), new Text("userId"));

        bs.addScanIterator(new IteratorSetting(50, "wri", WholeRowIterator.class));
        final Text colf = new Text();
        Map<String, List<Integer>> scoresByUser = new HashMap<>();
        for (Entry<Key, Value> entry : bs) {
            SortedMap<Key, Value> row = WholeRowIterator.decodeRow(entry.getKey(), entry.getValue());
            Iterator<Entry<Key, Value>> iter = row.entrySet().iterator();
            if (!iter.hasNext()) {
                // row was empty
                continue;
            }
            Entry<Key, Value> categoryEntry = iter.next();
            categoryEntry.getKey().getColumnFamily(colf);
            if (!colf.equals(categoryText)) {
                throw new IllegalArgumentException("Unknown!");
            }
            if (!categoryEntry.getValue().toString().equals("books")) {
                // not a book review
                continue;
            }

            if (!iter.hasNext()) {
                continue;
            }
            Entry<Key, Value> reviewScore = iter.next();
            if (!iter.hasNext()) {
                continue;
            }
            Entry<Key, Value> reviewUserId = iter.next();

            String userId = reviewUserId.getValue().toString();
            if (userId.equals("unknown")) {
                // filter unknow user id
                continue;
            }

            List<Integer> scores = scoresByUser.get(userId);
            if (null == scores) {
                scores = new ArrayList<>();
                scoresByUser.put(userId, scores);
            }
            scores.add(Float.valueOf(reviewScore.getValue().toString()).intValue());
        }

        for (Entry<String, List<Integer>> entry : scoresByUser.entrySet()) {
            int sum = 0;
            for (Integer val : entry.getValue()) {
                sum += val;
            }

            System.out.println(entry.getKey() + " => " + new Float(sum) / entry.getValue().size());
        }
    } finally {
        bs.close();
    }
}

From source file:joshelser.as2015.ingester.Ingester.java

public static void main(String[] args) throws Exception {
    JCommander commander = new JCommander();
    final Opts options = new Opts();
    commander.addObject(options);/*  w  ww .  j  a va  2s . co m*/

    commander.setProgramName("Amazon Review Parser");
    try {
        commander.parse(args);
    } catch (ParameterException ex) {
        commander.usage();
        System.err.println(ex.getMessage());
        System.exit(1);
    }

    Registry registry = new RegistryImpl();
    registry.add(new ReviewMapping());

    ClientConfiguration conf = ClientConfiguration.loadDefault();
    if (null != options.clientConfFile) {
        conf = new ClientConfiguration(new PropertiesConfiguration(options.clientConfFile));
    }
    conf.withInstance(options.instanceName).withZkHosts(options.zookeepers);

    ZooKeeperInstance inst = new ZooKeeperInstance(conf);
    Connector conn = inst.getConnector(options.user, new PasswordToken(options.password));
    if (!conn.tableOperations().exists(options.table)) {
        conn.tableOperations().create(options.table);
    }

    log.info("Writing data from {}", options.file);

    long count = 0;
    try (BufferedReader reader = new BufferedReader(new FileReader(options.file));
            Store store = new StoreImpl(registry, conn, options.table)) {
        List<String> schema = parseArray(readLine(reader));

        String[] record;
        while ((record = readLine(reader)) != null) {
            try {
                List<String> values = parseArray(record);
                CsvReview review = new CsvReview(schema, values);
                store.write(Collections.singleton(review));
                count++;
            } catch (Exception e) {
                log.error("Failed to parse '" + Arrays.toString(record) + "'", e);
            }
        }
    }

    log.info("Wrote {} records for {}", count, options.file);
}

From source file:com.tamingtext.tagging.LuceneCategoryExtractor.java

public static void main(String[] args) throws IOException {
    DefaultOptionBuilder obuilder = new DefaultOptionBuilder();
    ArgumentBuilder abuilder = new ArgumentBuilder();
    GroupBuilder gbuilder = new GroupBuilder();

    Option inputOpt = obuilder.withLongName("dir").withRequired(true)
            .withArgument(abuilder.withName("dir").withMinimum(1).withMaximum(1).create())
            .withDescription("The Lucene directory").withShortName("d").create();

    Option outputOpt = obuilder.withLongName("output").withRequired(false)
            .withArgument(abuilder.withName("output").withMinimum(1).withMaximum(1).create())
            .withDescription("The output directory").withShortName("o").create();

    Option maxOpt = obuilder.withLongName("max").withRequired(false)
            .withArgument(abuilder.withName("max").withMinimum(1).withMaximum(1).create())
            .withDescription(//www  . j  av a  2s  . co m
                    "The maximum number of documents to analyze.  If not specified, then it will loop over all docs")
            .withShortName("m").create();

    Option fieldOpt = obuilder.withLongName("field").withRequired(true)
            .withArgument(abuilder.withName("field").withMinimum(1).withMaximum(1).create())
            .withDescription("The field in the index").withShortName("f").create();

    Option helpOpt = obuilder.withLongName("help").withDescription("Print out help").withShortName("h")
            .create();

    Group group = gbuilder.withName("Options").withOption(inputOpt).withOption(outputOpt).withOption(maxOpt)
            .withOption(fieldOpt).create();

    try {
        Parser parser = new Parser();
        parser.setGroup(group);
        CommandLine cmdLine = parser.parse(args);

        if (cmdLine.hasOption(helpOpt)) {
            CommandLineUtil.printHelp(group);
            return;
        }

        File inputDir = new File(cmdLine.getValue(inputOpt).toString());

        if (!inputDir.isDirectory()) {
            throw new IllegalArgumentException(inputDir + " does not exist or is not a directory");
        }

        long maxDocs = Long.MAX_VALUE;
        if (cmdLine.hasOption(maxOpt)) {
            maxDocs = Long.parseLong(cmdLine.getValue(maxOpt).toString());
        }

        if (maxDocs < 0) {
            throw new IllegalArgumentException("maxDocs must be >= 0");
        }

        String field = cmdLine.getValue(fieldOpt).toString();

        PrintWriter out = null;
        if (cmdLine.hasOption(outputOpt)) {
            out = new PrintWriter(new FileWriter(cmdLine.getValue(outputOpt).toString()));
        } else {
            out = new PrintWriter(new OutputStreamWriter(System.out, "UTF-8"));
        }

        dumpDocumentFields(inputDir, field, maxDocs, out);

        IOUtils.close(Collections.singleton(out));
    } catch (OptionException e) {
        log.error("Exception", e);
        CommandLineUtil.printHelp(group);
    }

}