Java 8 Set - top ranked examples from Open Source projects

These code examples were ranked by Codota’s semantic indexing as the best open source examples for Java 8 Set class.

This code example shows how to use the following methods:add
	bhash.put(bbar, bcar);
	bhash.put(bcar, bbar);
	jedis.hmset(bfoo, bhash);
 
	Set<byte[]> bkeys = jedis.hkeys(bfoo);
	Set<byte[]> bexpected = new LinkedHashSet<byte[]>();
	bexpected.add(bbar);
	bexpected.add(bcar);
	assertEquals(bexpected, bkeys);
    } 
 
    @Test 
    public void hvals() { 
	Map<String, String> hash = new LinkedHashMap<String, String>();
	hash.put("bar", "car");
	hash.put("car", "bar");
	jedis.hmset("foo", hash);
 
	List<String> vals = jedis.hvals("foo");
	assertEquals(2, vals.size());
9
CodeRank
This code example shows how to use the following methods:add
    static final String UNEXPECTED_FAILURES_TABLE = "unexpectedFailures";
    static final String EXPECTED_PASSES_TABLE = "expextedPasses";
    static final String UNEXPECTED_PASSES_TABLE = "unexpextedPasses";
    private static final Set<String> TABLES_NAMES = new HashSet<String>();
    { 
        TABLES_NAMES.add(EXPECTED_FAILURES_TABLE);
        TABLES_NAMES.add(EXPECTED_PASSES_TABLE);
        TABLES_NAMES.add(UNEXPECTED_FAILURES_TABLE);
        TABLES_NAMES.add(UNEXPECTED_PASSES_TABLE);
    } 
 
    private static final void createTables(SQLiteDatabase db) {
        String cmd;
        for (String tableName : TABLES_NAMES) {
            cmd = "create table " + tableName + " ("
                    + KEY_ID + " integer primary key autoincrement, "
                    + KEY_PATH + " text not null, "
                    + KEY_BYTES + " blob not null);";
            db.execSQL(cmd);
        } 
8
CodeRank
This code example shows how to use the following methods:isEmpty, removeAll
            String name2, SortedSet<String> set2) {
        Set<String> onlyInSet1 = new TreeSet<String>(set1);
 
        onlyInSet1.removeAll(set2);
 
        Set<String> onlyInSet2 = new TreeSet<String>(set2);
        onlyInSet2.removeAll(set1);
 
        if (!onlyInSet1.isEmpty() || !onlyInSet2.isEmpty()) {
            fail(String.format("in %s only: %s\nin %s only: %s", name1, onlyInSet1, name2, onlyInSet2));
        } 
 
        assertEquals(set2, set1);
    } 
 
    protected SortedSet<String> findAllPropertyNames(Class<?> clazz) throws Exception {
        SortedSet<String> names = new TreeSet<String>();
        for (PropertyDescriptor propDesc : getBeanInfo(clazz).getPropertyDescriptors()) {
            if (propDesc == null
                    || propDesc.getWriteMethod() == null) {
8
CodeRank
This code example shows how to use the following methods:add
 
    Object snapshotValue = snapshot.get(key);
    if (snapshotValue == null) {
      final OIdentifiable storedValue = indexEngine.get(key);
 
      final Set<OIdentifiable> values = new LinkedHashSet<OIdentifiable>();
 
      if (storedValue != null)
        values.add(storedValue.getIdentity());
 
      values.add(value.getIdentity());
 
      snapshot.put(key, values);
    } else if (snapshotValue instanceof Set) {
      final Set<OIdentifiable> values = (Set<OIdentifiable>) snapshotValue;
 
      values.add(value.getIdentity());
    } else { 
      final Set<OIdentifiable> values = new LinkedHashSet<OIdentifiable>();
 
8
CodeRank
This code example shows how to use the following methods:add
  public static final Pattern SCALAR_PATTERN = Pattern.compile("^\\d*$");
  public static final Pattern FRACTIONAL_SCALAR_PATTERN = Pattern.compile("^\\d\\.\\d*$");
  public static Set<String> TIMES = new HashSet<String>();
 
  static { 
    Scalar.TIMES.add("am");
    Scalar.TIMES.add("pm");
    Scalar.TIMES.add("morning");
    Scalar.TIMES.add("afternoon");
    Scalar.TIMES.add("evening");
    Scalar.TIMES.add("night");
  } 
 
  public Scalar(Number type) {
    super(type);
  } 
 
  public static List<Token> scan(List<Token> tokens, Options options) {
    for (int i = 0; i < tokens.size(); i++) {
      Token token = tokens.get(i);
8
CodeRank
This code example shows how to use the following methods:isEmpty, iterator
  public Iterator<T> iterator() {
    return ids.iterator();
  } 
 
  public synchronized T choose() { 
    if (!ids.isEmpty()) {
      if (iter == null || !iter.hasNext()) {
        iter = ids.iterator();
      } 
      try { 
        return iter.next();
      } catch (NoSuchElementException e) {
        return null; 
      } 
    } else { 
      return null; 
    } 
  } 
} 
8
CodeRank
This code example shows how to use the following methods:isEmpty, size
    @Override 
    protected void recognizeArguments(CommandContext ctx) throws CommandFormatException {
 
        final ParsedCommandLine args = ctx.getParsedCommandLine();
        final Set<String> propertyNames = args.getPropertyNames();
        if(!propertyNames.isEmpty()) {
            final Collection<String> names;
            if(helpArg.isPresent(args)) {
                if(propertyNames.size() == 1) {
                    return; 
                } 
                names = new ArrayList<String>(propertyNames);
                names.remove(helpArg.getFullName());
                names.remove(helpArg.getShortName());
            } else { 
                names = propertyNames;
            } 
            throw new CommandFormatException("Unrecognized argument names: " + names);
        } 
    } 
8
CodeRank
This code example shows how to use the following methods:add
                metaData.setRoleName(getElementText(reader, propertyReplacer));
            else if (localName.equals(Element.PRINCIPAL_NAME.getLocalName())) {
                Set<String> principalNames = metaData.getPrincipals();
                if (principalNames == null) {
                    principalNames = new HashSet<String>();
                    metaData.setPrincipals(principalNames);
                } 
                principalNames.add(getElementText(reader, propertyReplacer));
            } 
            else 
                throw unexpectedElement(reader);
        } else { 
            super.processElement(metaData, reader, propertyReplacer);
        } 
    } 
 
} 
8
CodeRank
This code example shows how to use the following methods:contains, size
        assertFalse(handler.isRequestComplete());
 
        assertEquals("read-resource", handler.getOperationName());
 
        Set<String> argNames = handler.getPropertyNames();
        assertEquals(2, argNames.size());
        assertTrue(argNames.contains("recursive"));
        assertEquals("true", handler.getPropertyValue("recursive"));
        assertTrue(argNames.contains("other"));
    } 
 
    @Test 
    public void testNameValueSeparatorNameAndValueSeparator() throws Exception { 
        DefaultCallbackHandler handler = new DefaultCallbackHandler();
 
        parseOperation(":read-resource(recursive=true,other=", handler);
 
        assertFalse(handler.hasAddress());
        assertTrue(handler.hasOperationName());
        assertTrue(handler.hasProperties());
8
CodeRank
This code example shows how to use the following methods:add, contains, remove
      return super.getResult(); 
    } 
  } 
 
  private static void addItemToResult(Object o, Set<Object> accepted, Set<Object> rejected) {
    if (!accepted.contains(o) && !rejected.contains(o)) {
      accepted.add(o);
    } else { 
      accepted.remove(o);
      rejected.add(o);
    } 
  } 
 
  private static void addItemsToResult(Collection<Object> co, Set<Object> accepted, Set<Object> rejected) {
    for (Object o : co) {
      addItemToResult(o, accepted, rejected);
    } 
  } 
 
  public String getSyntax() {
8
CodeRank
This code example shows how to use the following methods:contains, size
        assertEquals("console-handler", node.getType());
        assertEquals("CONSOLE", node.getName());
        assertFalse(i.hasNext());
 
        Set<String> args = handler.getPropertyNames();
        assertEquals(2, args.size());
        assertTrue(args.contains("name"));
        assertEquals("filter-spec", handler.getPropertyValue("name"));
        assertTrue(args.contains("value"));
        assertEquals("\"substituteAll(\\\"JBAS\\\",\\\"DUMMY\\\")\"", handler.getPropertyValue("value"));
    } 
 
    protected void parse(String opReq, DefaultCallbackHandler handler) throws CommandFormatException {
        parser.parse(opReq, handler);
    } 
} 
8
CodeRank
This code example shows how to use the following methods:add, contains
 
  public Object execute(final OIdentifiable iCurrentRecord, Object iCurrentResult, final Object[] iParameters,
      OCommandContext iContext) {
    final Object value = iParameters[0];
 
    if (value != null && !context.contains(value)) {
      context.add(value);
      return value;
    } 
 
    return null; 
  } 
 
  @Override 
  public boolean filterResult() { 
    return true; 
  } 
 
  public String getSyntax() {
    return "Syntax error: distinct(<field>)"; 
8
CodeRank
This code example shows how to use the following methods:add
    @Test 
    public void smembers() { 
        jedis.sadd("foo", "a"); 
        jedis.sadd("foo", "b"); 
 
        Set<String> expected = new HashSet<String>();
        expected.add("a");
        expected.add("b");
 
        Set<String> members = jedis.smembers("foo");
 
        assertEquals(expected, members);
 
        // Binary 
        jedis.sadd(bfoo, ba);
        jedis.sadd(bfoo, bb);
 
        Set<byte[]> bexpected = new HashSet<byte[]>();
        bexpected.add(bb);
        bexpected.add(ba);
8
CodeRank
This code example shows how to use the following methods:add
        jedis.zadd("foo", 1d, "a"); 
        jedis.zadd("foo", 2d, "b"); 
 
        long status = jedis.zrem("foo", "a");
 
        Set<String> expected = new LinkedHashSet<String>();
        expected.add("b");
 
        assertEquals(1, status);
        assertEquals(expected, jedis.zrange("foo", 0, 100));
 
        status = jedis.zrem("foo", "bar");
 
        assertEquals(0, status);
 
        // Binary 
        jedis.zadd(bfoo, 1d, ba);
        jedis.zadd(bfoo, 2d, bb);
 
        long bstatus = jedis.zrem(bfoo, ba);
8
CodeRank
This code example shows how to use the following methods:contains, remove
        } 
    } 
 
    public synchronized void undeploy(@Observes BeforeStop event, Container container, ServiceArchiveHolder archiveHolder) {
        // clean up if we deployed to this container? 
        if (serviceArchiveDeployed.contains(container.getName())) {
            try { 
                Archive<?> serviceArchive = archiveHolder.getArchive();
                log.infof("Undeploy arquillian service: %s", serviceArchive);
                DeployableContainer<?> deployableContainer = container.getDeployableContainer();
                deployableContainer.undeploy(serviceArchive);
                serviceArchiveDeployed.remove(container.getName());
            } catch (Throwable th) {
                log.error("Cannot undeploy arquillian service", th);
            } 
        } 
    } 
} 
8
CodeRank
This code example shows how to use the following methods:add
     */ 
    @Test 
    public void testCreateSection() { 
        Configuration config = getConfig();
 
        Set<String> set = new HashSet<String>();
        set.add("this");
        set.add("this.test.sub");
        set.add("this.test");
        set.add("this.test.other");
 
        config.createSection("this.test.sub");
        config.createSection("this.test.other");
 
        assertEquals(set, config.getKeys(true));
    } 
 
    /** 
     * Test of getDefaults method, of class Configuration. 
     */ 
8
CodeRank
This code example shows how to use the following methods:iterator
        return mergeStats;
    } 
 
    @Override 
    public Set<OnGoingMerge> onGoingMerges() {
        for (CustomConcurrentMergeScheduler scheduler : schedulers) {
            return scheduler.onGoingMerges();
        } 
        return ImmutableSet.of(); 
    } 
 
    public static class CustomConcurrentMergeScheduler extends TrackingConcurrentMergeScheduler { 
 
        private final ShardId shardId;
 
        private final ConcurrentMergeSchedulerProvider provider;
 
        private CustomConcurrentMergeScheduler(ESLogger logger, ShardId shardId, ConcurrentMergeSchedulerProvider provider) {
            super(logger);
            this.shardId = shardId;
8
CodeRank
This code example shows how to use the following methods:add
    static Set<String> readPreferenceKeys = new HashSet<String>();
    static Set<String> writeConcernKeys = new HashSet<String>();
    static Set<String> allKeys = new HashSet<String>();
 
    static { 
        generalOptionsKeys.add("maxpoolsize");
        generalOptionsKeys.add("waitqueuemultiple");
        generalOptionsKeys.add("waitqueuetimeoutms");
        generalOptionsKeys.add("connecttimeoutms");
        generalOptionsKeys.add("sockettimeoutms");
        generalOptionsKeys.add("sockettimeoutms");
        generalOptionsKeys.add("autoconnectretry");
        generalOptionsKeys.add("ssl");
 
        readPreferenceKeys.add("slaveok");
        readPreferenceKeys.add("readpreference");
        readPreferenceKeys.add("readpreferencetags");
 
        writeConcernKeys.add("safe");
        writeConcernKeys.add("w");
8
CodeRank
This code example shows how to use the following methods:iterator, size
        Employee emp = new Employee();
        emp.setEmail("MADHUMITA");
 
        Set<ConstraintViolation<Employee>> constraintViolations = validator.validate(emp);
 
        assertEquals("Wrong number of constraints", constraintViolations.size(), 1);
        assertEquals(CustomMessageInterpolator.MESSAGE, constraintViolations.iterator().next().getMessage());
    } 
 
    private static class CustomMessageInterpolator implements MessageInterpolator { 
 
        public static final String MESSAGE = "Message created by custom interpolator";
 
        @Override 
        public String interpolate(String messageTemplate, Context context) {
            return MESSAGE;
        } 
 
        @Override 
        public String interpolate(String messageTemplate, Context context, Locale locale) {
8
CodeRank
This code example shows how to use the following methods:add
		BAD_SQL_GRAMMAR_CODES.add("2A");	// Syntax error direct SQL 
		BAD_SQL_GRAMMAR_CODES.add("37");	// Syntax error dynamic SQL 
		BAD_SQL_GRAMMAR_CODES.add("42");	// General SQL syntax error 
		BAD_SQL_GRAMMAR_CODES.add("65");	// Oracle: unknown identifier 
 
		DATA_INTEGRITY_VIOLATION_CODES.add("01");	// Data truncation 
		DATA_INTEGRITY_VIOLATION_CODES.add("02");	// No data found 
		DATA_INTEGRITY_VIOLATION_CODES.add("22");	// Value out of range 
		DATA_INTEGRITY_VIOLATION_CODES.add("23");	// Integrity constraint violation 
		DATA_INTEGRITY_VIOLATION_CODES.add("27");	// Triggered data change violation 
		DATA_INTEGRITY_VIOLATION_CODES.add("44");	// With check violation 
 
		DATA_ACCESS_RESOURCE_FAILURE_CODES.add("08");	 // Connection exception 
		DATA_ACCESS_RESOURCE_FAILURE_CODES.add("53");	 // PostgreSQL: insufficient resources (e.g. disk full) 
		DATA_ACCESS_RESOURCE_FAILURE_CODES.add("54");	 // PostgreSQL: program limit exceeded (e.g. statement too complex) 
		DATA_ACCESS_RESOURCE_FAILURE_CODES.add("57");	 // DB2: out-of-memory exception / database not started 
		DATA_ACCESS_RESOURCE_FAILURE_CODES.add("58");	 // DB2: unexpected system error 
 
		TRANSIENT_DATA_ACCESS_RESOURCE_CODES.add("JW");	 // Sybase: internal I/O error 
		TRANSIENT_DATA_ACCESS_RESOURCE_CODES.add("JZ");	 // Sybase: unexpected I/O error 
8
CodeRank
This code example shows how to use the following methods:size, toArray
  public ApplicationId getApplicationID() { 
    return applicationId;
  } 
 
  public String[] getHosts() {
    return hosts.toArray(new String[hosts.size()]);
  } 
   
  public String[] getRacks() {
    return racks.toArray(new String[racks.size()]);
  } 
   
  public boolean canSchedule(NodeType type, String hostName) {
    if (type == NodeType.NODE_LOCAL) { 
      return hosts.contains(hostName);
    } else if (type == NodeType.RACK_LOCAL) {
      return racks.contains(Application.resolve(hostName));
    }  
     
    return true; 
8
CodeRank
This code example shows how to use the following methods:contains
        testMethodAnnotations.add("Lorg/testng/annotations/AfterGroups;");
        testMethodAnnotations.add("Lorg/testng/annotations/Factory;");
    } 
 
    public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
        if (testMethodAnnotations.contains(desc)) {
            testClassDetecter.setTest(true);
        } 
        return null; 
    } 
} 
7
CodeRank
This code example shows how to use the following methods:size, toArray
 
    @Override 
    public void mutate() { 
        // We only ever have to perform a replace once within a batch 
        if (this.mutated.compareAndSet(false, true)) {
            this.invoker.invoke(this.cache, new MutateOperation<>(this.id, this.value), this.flags.toArray(new Flag[this.flags.size()]));
        } 
    } 
 
    public static boolean isMutable(Object object) {
        for (Object value: IMMUTABLE_VALUES) {
            if (object == value) return false;
        } 
        for (Class<?> immutableClass: IMMUTABLE_TYPES) {
            if (immutableClass.isInstance(object)) return false;
        } 
        return !object.getClass().isAnnotationPresent(Immutable.class);
    } 
} 
7
CodeRank
This code example shows how to use the following methods:add, contains
 
  @SuppressWarnings("unused") 
  // for input parameter ignored. 
  @JsonAnySetter 
  public void setUnknownAttribute(String attributeName, Object ignored) {
    if (!alreadySeenAnySetterAttributes.contains(attributeName)) {
      alreadySeenAnySetterAttributes.add(attributeName);
      System.err.println("In LoggedJob, we saw the unknown attribute "
          + attributeName + ".");
    } 
  } 
 
  public double getRelativeRanking() { 
    return relativeRanking;
  } 
 
  void setRelativeRanking(double relativeRanking) {
    this.relativeRanking = relativeRanking;
  } 
 
8
CodeRank
This code example shows how to use the following methods:add
  } 
 
  @Test 
  public void testBatchGetWithSimpleKey() throws Exception 
  { 
    Set<String> keys = new HashSet<String>();
    keys.add(key1());
    keys.add(key2());
    BatchGetRequest<Message> req = new StringKeysBuilders().batchGet().ids(keys).build();
    BatchResponse<Message> response = REST_CLIENT.sendRequest(req).get().getEntity();
    Map<String, Message> results = response.getResults();
    Assert.assertEquals(results.get(key1()).getMessage(), key1(), "Message should match key for key1");
    Assert.assertEquals(results.get(key2()).getMessage(), key2(), "Message should match key for key2");
  } 
 
  @Test 
  public void testGetWithAssociationKey() throws Exception 
  { 
    CompoundKey key = new CompoundKey();
    key.append("src", key1());
8
CodeRank
This code example shows how to use the following methods:iterator, size
 
    @Test 
    public void testResource() throws Exception { 
        // There's one bean of type CDIResource and it's scope is @RequestScoped (this is resteasy-cdi specific) 
        Set<Bean<?>> beans = beanManager.getBeans(CDIResource.class); 
        assertEquals(1, beans.size()); 
        assertEquals(RequestScoped.class, beans.iterator().next().getScope()); 
    } 
 
    @Test 
    public void testApplication() throws Exception { 
        // There's one bean of type CDIApplication and it's scope is @ApplicationScoped 
        Set<Bean<?>> beans = beanManager.getBeans(CDIApplication.class); 
        assertEquals(1, beans.size()); 
        assertEquals(ApplicationScoped.class, beans.iterator().next().getScope()); 
    } 
 
    @Test 
    public void testProvider() throws Exception { 
        // There's one bean of type CDIProvider and it's scope is @ApplicationScoped 
8
CodeRank
This code example shows how to use the following methods:isEmpty, iterator
    private final Subject subject;
 
    public RealmSubjectUserInfo(Subject subject) {
        this.subject = subject;
        Set<RealmUser> users = subject.getPrincipals(RealmUser.class);
        userName = users.isEmpty() ? null : users.iterator().next().getName();
    } 
 
    public String getUserName() {
        return userName;
    } 
 
    public Collection<Principal> getPrincipals() {
        return subject.getPrincipals();
    } 
 
    public Subject getSubject() {
        return subject;
    } 
 
8
CodeRank
This code example shows how to use the following methods:size, toArray
        Set<String> groups = userGroups.get(player.toLowerCase());
        if (groups == null) {
            return new String[0];
        } 
 
        return groups.toArray(new String[groups.size()]);
    } 
 
    public boolean hasPermission(OfflinePlayer player, String permission) {
        return hasPermission(player.getName(), permission);
    } 
 
    public boolean hasPermission(String worldName, OfflinePlayer player, String permission) {
        return hasPermission(worldName, player.getName(), permission);
    } 
 
    public boolean inGroup(OfflinePlayer player, String group) {
        return inGroup(player.getName(), group);
    } 
 
7
CodeRank
This code example shows how to use the following methods:contains, size
                .put("foo", "abc") 
                .put("foo.bar", "def") 
                .put("foo.baz", "ghi").build(); 
 
        Set<String> names = settings.names();
        assertThat(names.size(), equalTo(2));
        assertTrue(names.contains("bar"));
        assertTrue(names.contains("foo"));
 
        Settings fooSettings = settings.getAsSettings("foo"); 
        names = fooSettings.names();
        assertThat(names.size(), equalTo(2));
        assertTrue(names.contains("bar"));
        assertTrue(names.contains("baz"));
 
    } 
} 
7
CodeRank
This code example shows how to use the following methods:add
     
    private static final Set<String> stringSet;
     
    static { 
    	stringSet = new HashSet<String>();
    	stringSet.add( "string1" );
    	stringSet.add( "string2" );
    	stringSet.add( "string3" );
    } 
     
    @Before 
    public void setUp() { 
        content = new HashMap<String, Map<String, Object>>();
 
        sharedPreferences = new TestSharedPreferences(content, FILENAME, 3);
        editor = sharedPreferences.edit();
        editor.putBoolean("boolean", true);
        editor.putFloat("float", 1.1f);
        editor.putInt("int", 2);
        editor.putLong("long", 3l);
8
CodeRank

Related Java 8 Set Questions & Answers:

See Code Examples for Java 8 Set Methods: