List of usage examples for java.util Set size
int size();
From source file:com.pinterest.terrapin.controller.HdfsManager.java
static double calculateDeviationForResource(String resource, IdealState idealState, RoutingTableProvider routingTableProvider) { Set<String> partitions = idealState.getPartitionSet(); int totalAssignments = 0, totalDeviations = 0; // Check if the external view has deviated from the actual view. for (String partition : partitions) { // Make a copy of the instance mapping in the ideal state. Set<String> idealInstances = new HashSet(idealState.getInstanceSet(partition)); totalAssignments += idealInstances.size(); // Now check against our real state and count the amount of deviating // assignments. List<InstanceConfig> currentInstanceConfigs = routingTableProvider.getInstances(resource, partition, "ONLINE"); Set<String> currentInstances = Sets.newHashSetWithExpectedSize(currentInstanceConfigs.size()); if (currentInstanceConfigs != null) { for (InstanceConfig instanceConfig : currentInstanceConfigs) { currentInstances.add(instanceConfig.getHostName()); }//from ww w.ja v a2 s . c om } idealInstances.removeAll(currentInstances); totalDeviations += idealInstances.size(); } return (double) totalDeviations / totalAssignments; }
From source file:net.minecraftforge.fml.common.registry.VillagerRegistry.java
/** * Hook called when spawning a Villager, sets it's profession to a random registered profession. * * @param entity The new entity/*from w w w .j av a 2 s .co m*/ * @param rand The world's RNG */ public static void setRandomProfession(EntityVillager entity, Random rand) { Set<String> entries = INSTANCE.professions.getKeys(); int prof = rand.nextInt(entries.size()); //TODO: Grab id range from internal registry entity.setProfession(rand.nextInt(5)); }
From source file:net.sf.morph.util.TestUtils.java
public static boolean equals(Object object1, Object object2) { if (log.isTraceEnabled()) { log.trace("Testing for equality between " + ObjectUtils.getObjectDescription(object1) + " and " + ObjectUtils.getObjectDescription(object2)); }/*from w w w. j a v a2 s. c o m*/ // if both objects are == (incl. null) they are equal if (object1 == object2) { return true; } // if one object is null and the other is not, the two objects aren't // equal if (object1 == null || object2 == null) { return false; } if (object1 instanceof Calendar && object2 instanceof Calendar) { return equals(((Calendar) object1).getTime(), ((Calendar) object2).getTime()); } if (object1 instanceof Comparable && object1.getClass() == object2.getClass()) { return ((Comparable) object1).compareTo(object2) == 0; } if (object1 instanceof Map.Entry && object2 instanceof Map.Entry) { if (object1.getClass() != object2.getClass()) { return false; } Map.Entry me1 = (Map.Entry) object1; Map.Entry me2 = (Map.Entry) object2; return equals(me1.getKey(), me2.getKey()) && equals(me1.getValue(), me2.getValue()); } // if both objects are arrays if (object1.getClass().isArray() && object2.getClass().isArray()) { // if the arrays aren't of the same class, the two objects aren't // equal if (object1.getClass() != object2.getClass()) { return false; } // else, same type of array // if the arrays are different sizes, they aren't equal if (Array.getLength(object1) != Array.getLength(object2)) { return false; } // else arrays are the same size // iterate through the arrays and check if all elements are // equal for (int i = 0; i < Array.getLength(object1); i++) { // if one item isn't equal to the other if (!equals(Array.get(object1, i), Array.get(object2, i))) { // the arrays aren't equal return false; } } // if we iterated through both arrays and found no items // that weren't equal to each other, the collections are // equal return true; } if (object1 instanceof Iterator && object2 instanceof Iterator) { Iterator iterator1 = (Iterator) object1; Iterator iterator2 = (Iterator) object2; while (iterator1.hasNext()) { if (!iterator2.hasNext()) { return false; } // if one item isn't equal to the other if (!equals(iterator1.next(), iterator2.next())) { // the arrays aren't equal return false; } } // if we iterated through both collections and found // no items that weren't equal to each other, the // collections are equal return !iterator2.hasNext(); } if (object1 instanceof Enumeration && object2 instanceof Enumeration) { return equals(new EnumerationIterator((Enumeration) object1), new EnumerationIterator((Enumeration) object2)); } if ((object1 instanceof List && object2 instanceof List) || (object1 instanceof SortedSet && object2 instanceof SortedSet)) { // if the collections aren't of the same type, they aren't equal if (object1.getClass() != object2.getClass()) { return false; } // else same type of collection return equals(((Collection) object1).iterator(), ((Collection) object2).iterator()); } if (object1 instanceof Set && object2 instanceof Set) { // if the sets aren't of the same type, they aren't equal if (object1.getClass() != object2.getClass()) { return false; } // else same type of set Set set1 = (Set) object1; Set set2 = (Set) object2; // if the sets aren't the same size, they aren't equal if (set1.size() != set2.size()) { return false; } // else sets are the same size Iterator iterator1 = set1.iterator(); while (iterator1.hasNext()) { Object next = iterator1.next(); if (!contains(set2, next)) { return false; } } return true; } if (object1 instanceof Map && object2 instanceof Map) { return equals(((Map) object1).entrySet(), ((Map) object2).entrySet()); } if (object1.getClass() == object2.getClass() && object1 instanceof StringBuffer) { return object1.toString().equals(object2.toString()); } // for primitives, use their equals methods if (object1.getClass() == object2.getClass() && (object1 instanceof String || object1 instanceof Number || object1 instanceof Boolean || //object1 instanceof StringBuffer || object1 instanceof Character)) { return object1.equals(object2); } // for non-primitives, compare field-by-field return MorphEqualsBuilder.reflectionEquals(object1, object2); }
From source file:py.una.pol.karaku.test.util.TestUtils.java
/** * Retorna la lista de entidades relacionadas a una base. * //from ww w .j av a 2 s . c om * @param base * entidad base * @return array con todas las entidades que se pueden acceder desde base. */ public static Class<?>[] getReferencedClasses(Class<?>... base) { LOG.info("Scanning for classes with relations with '{}'", base); Set<Class<?>> result = new HashSet<Class<?>>(10); for (Class<?> clasz : base) { result.add(clasz); getReferencedClasses(clasz, result); } LOG.info("Found '{}' classes with relations with '{}'", result.size(), base); return result.toArray(new Class<?>[result.size()]); }
From source file:net.audumla.climate.ClimateDataFactory.java
/** * Replaces the climate data with a writable version. * * @param cd the existing climate data bean * @return the climate data// w w w . j a v a 2 s . c o m */ public static WritableClimateData convertToWritableClimateData(ClimateData cd) { if (cd == null) { return null; } Set<Class<?>> interfaces = new LinkedHashSet<Class<?>>(); interfaces.addAll(ClassUtils.getAllInterfaces(cd.getClass())); return BeanUtils.convertBean(cd, WritableClimateData.class, interfaces.toArray(new Class<?>[interfaces.size()])); }
From source file:de.unisb.cs.st.javalanche.mutation.results.MutationCoverageFile.java
public static void saveCoverageData(Map<Long, Set<String>> coverageData) { COVERAGE_DIR.mkdirs();// w ww. j a v a2 s . c o m coveredMutations = new HashSet<Long>(); BiMap<String, Integer> allTests = getAllTests(coverageData.values()); SerializeIo.serializeToFile(allTests, FILE_MAP); Set<Entry<Long, Set<String>>> entrySet = coverageData.entrySet(); for (Entry<Long, Set<String>> entry : entrySet) { Set<Integer> testIDs = new HashSet<Integer>(); for (String testName : entry.getValue()) { if (testName != null) { testIDs.add(allTests.get(testName)); } } Long id = entry.getKey(); if (testIDs.size() > 0) { coveredMutations.add(id); logger.debug("Adding covered mutation" + id); Collection<Long> collection = baseMutations.get(id); if (collection.size() > 0) { logger.debug("Adding children of base mutation" + collection); coveredMutations.addAll(collection); } } SerializeIo.serializeToFile(testIDs, new File(COVERAGE_DIR, "" + id)); } logger.info("Saving Ids of Covered Mutations " + coveredMutations.size()); SerializeIo.serializeToFile(coveredMutations, COVERED_FILE); }
From source file:de.ifgi.fmt.utils.Utils.java
/** * //from www . j a v a2s.co m * @param <T> * @param list * @return */ public static <T> Set<T> castToSuperType(final Set<? extends T> list) { return new HashSet<T>(list.size()) { { addAll(list); } }; }
From source file:io.lavagna.service.PermissionService.java
private static MapSqlParameterSource[] from(Role role, Set<Permission> l) { List<MapSqlParameterSource> ret = new ArrayList<>(l.size()); for (Permission p : l) { ret.add(new MapSqlParameterSource("permission", p.toString()).addValue("roleName", role.getName())); }//ww w .j a va 2s. c om return ret.toArray(new MapSqlParameterSource[ret.size()]); }
From source file:com.adobe.acs.commons.analysis.jcrchecksum.impl.JSONGenerator.java
public static void generateJSON(Session session, Set<String> paths, ChecksumGeneratorOptions opts, JsonWriter out) throws RepositoryException, IOException { Node node = null;/*from w w w .j av a 2s . c om*/ if (paths.size() > 1) { out.beginArray(); } for (String path : paths) { out.beginObject(); try { if (session.itemExists(path)) { Item item = session.getItem(path); if (item.isNode()) { node = (Node) item; } } traverseTree(node, opts, out); } catch (PathNotFoundException e) { out.name("ERROR"); out.value("WARN: Path doesn't exist: " + path); } catch (RepositoryException e) { out.name("ERROR"); out.value("Unable to read path: " + e.getMessage()); } finally { out.endObject(); } } if (paths.size() > 1) { out.endArray(); } }
From source file:com.github.strawberry.redis.RedisLoader.java
private static Option loadFromRedis(JedisPool pool, final Field field, final Redis annotation) { return using(pool)._do(new F<Jedis, Option>() { @Override// w w w. j a va2 s .co m public Option f(Jedis jedis) { Object value = null; Class<?> fieldType = field.getType(); String pattern = annotation.value(); boolean allowNull = annotation.allowNull(); Set<String> redisKeys = Sets.newTreeSet(jedis.keys(pattern)); if (redisKeys.size() == 1) { String redisKey = Iterables.getOnlyElement(redisKeys); if (fieldType.equals(char[].class)) { value = jedis.get(redisKey).toCharArray(); } else if (fieldType.equals(Character[].class)) { value = ArrayUtils.toObject(jedis.get(redisKey).toCharArray()); } else if (fieldType.equals(char.class) || fieldType.equals(Character.class)) { String toConvert = jedis.get(redisKey); if (toConvert.length() == 1) { value = jedis.get(redisKey).charAt(0); } else { throw ConversionException.of(toConvert, redisKey, fieldType); } } else if (fieldType.equals(String.class)) { value = jedis.get(redisKey); } else if (fieldType.equals(byte[].class)) { value = jedis.get(redisKey.getBytes()); } else if (fieldType.equals(Byte[].class)) { value = ArrayUtils.toObject(jedis.get(redisKey.getBytes())); } else if (fieldType.equals(boolean.class) || fieldType.equals(Boolean.class)) { String toConvert = jedis.get(redisKey); if (BOOLEAN.matcher(toConvert).matches()) { value = TRUE.matcher(toConvert).matches(); } else { throw ConversionException.of(toConvert, redisKey, fieldType); } } else if (Map.class.isAssignableFrom(fieldType)) { value = mapOf(field, jedis, redisKey); } else if (Collection.class.isAssignableFrom(fieldType)) { value = collectionOf(field, jedis, redisKey); } else { String toConvert = jedis.get(redisKey); try { if (fieldType.equals(byte.class) || fieldType.equals(Byte.class)) { value = Byte.parseByte(jedis.get(redisKey)); } else if (fieldType.equals(short.class) || fieldType.equals(Short.class)) { value = Short.parseShort(toConvert); } else if (fieldType.equals(int.class) || fieldType.equals(Integer.class)) { value = Integer.parseInt(toConvert); } else if (fieldType.equals(long.class) || fieldType.equals(Long.class)) { value = Long.parseLong(toConvert); } else if (fieldType.equals(BigInteger.class)) { value = new BigInteger(toConvert); } else if (fieldType.equals(float.class) || fieldType.equals(Float.class)) { value = Float.parseFloat(toConvert); } else if (fieldType.equals(double.class) || fieldType.equals(Double.class)) { value = Double.parseDouble(toConvert); } else if (fieldType.equals(BigDecimal.class)) { value = new BigDecimal(toConvert); } } catch (NumberFormatException exception) { throw ConversionException.of(exception, toConvert, redisKey, fieldType); } } } else if (redisKeys.size() > 1) { if (Map.class.isAssignableFrom(fieldType)) { value = nestedMapOf(field, jedis, redisKeys); } else if (Collection.class.isAssignableFrom(fieldType)) { value = nestedCollectionOf(field, jedis, redisKeys); } } else { if (!allowNull) { value = nonNullValueOf(fieldType); } } return Option.fromNull(value); } }); }