Example usage for java.util Set size

List of usage examples for java.util Set size

Introduction

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

Prototype

int size();

Source Link

Document

Returns the number of elements in this set (its cardinality).

Usage

From source file:com.asakusafw.runtime.stage.output.StageOutputDriver.java

private static void addOutput(Job job, String name, Class<?> formatClass, Class<?> keyClass,
        Class<?> valueClass) {
    assert job != null;
    assert name != null;
    assert formatClass != null;
    assert keyClass != null;
    assert valueClass != null;
    if (isValidName(name) == false) {
        throw new IllegalArgumentException(MessageFormat.format("Output name \"{0}\" is not valid", name));
    }//from w w  w.  j  av a2  s. c  o m
    Configuration conf = job.getConfiguration();
    Set<String> names = new TreeSet<>(conf.getStringCollection(K_NAMES));
    if (names.contains(name)) {
        throw new IllegalArgumentException(
                MessageFormat.format("Output name \"{0}\" is already declared", name));
    }
    names.add(name);
    conf.setStrings(K_NAMES, names.toArray(new String[names.size()]));
    conf.setClass(getPropertyName(K_FORMAT_PREFIX, name), formatClass, OutputFormat.class);
    conf.setClass(getPropertyName(K_KEY_PREFIX, name), keyClass, Object.class);
    conf.setClass(getPropertyName(K_VALUE_PREFIX, name), valueClass, Object.class);
}

From source file:net.sourceforge.vulcan.spring.jdbc.HistoryQueryBuilder.java

static void buildQuery(String selectClause, BuildOutcomeQueryDto dto, BuilderQuery query) {
    final Set<String> projectNames = dto.getProjectNames();
    if (projectNames == null || projectNames.isEmpty()) {
        throw new IllegalArgumentException("Must query for at least one project name");
    }/*from  w  w  w . java  2  s .c  om*/

    final List<? super Object> params = new ArrayList<Object>();

    final StringBuilder sb = new StringBuilder();

    sb.append("where project_names.name");

    query.declareParameter(new SqlParameter(Types.VARCHAR));

    if (projectNames.size() == 1) {
        sb.append("=?");
        params.addAll(projectNames);
    } else {
        sb.append(" in (?");
        for (int i = 1; i < projectNames.size(); i++) {
            sb.append(",?");
            query.declareParameter(new SqlParameter(Types.VARCHAR));
        }
        sb.append(")");

        final List<String> sorted = new ArrayList<String>(projectNames);
        Collections.sort(sorted);
        params.addAll(sorted);
    }

    if (dto.getMinDate() != null) {
        sb.append(" and completion_date>=?");
        params.add(dto.getMinDate());
        query.declareParameter(new SqlParameter(Types.TIMESTAMP));
    }

    if (dto.getMaxDate() != null) {
        sb.append(" and completion_date<?");
        params.add(dto.getMaxDate());
        query.declareParameter(new SqlParameter(Types.TIMESTAMP));
    }

    if (dto.getMinBuildNumber() != null) {
        sb.append(" and build_number>=?");
        params.add(dto.getMinBuildNumber());
        query.declareParameter(new SqlParameter(Types.INTEGER));
    }

    if (dto.getMaxBuildNumber() != null) {
        sb.append(" and build_number<=?");
        params.add(dto.getMaxBuildNumber());
        query.declareParameter(new SqlParameter(Types.INTEGER));
    }

    final Set<Status> statuses = dto.getStatuses();
    if (statuses != null && !statuses.isEmpty()) {
        query.declareParameter(new SqlParameter(Types.VARCHAR));

        sb.append(" and status in (?");
        for (int i = 1; i < statuses.size(); i++) {
            query.declareParameter(new SqlParameter(Types.VARCHAR));
            sb.append(",?");
        }
        sb.append(")");

        params.addAll(statuses);
    }

    if (dto.getUpdateType() != null) {
        query.declareParameter(new SqlParameter(Types.VARCHAR));
        sb.append(" and update_type=?");
        params.add(dto.getUpdateType().name());
    }

    if (isNotBlank(dto.getRequestedBy())) {
        query.declareParameter(new SqlParameter(Types.VARCHAR));
        sb.append(" and requested_by=?");
        params.add(dto.getRequestedBy());
    }

    query.setParameterValues(params.toArray());

    query.setSql(selectClause + sb.toString());
}

From source file:net.sf.morph.util.ContainerUtils.java

/**
 * Returns the intersection of multiple arrays as an array.  Implementation is O(n<sup>3</sup>).
 *
 * @param arrays/*from ww  w.j a v a  2 s.  c o m*/
 *            a List of arrays
 * @param componentType
 *            the runtime type of the returned array
 * @return the intersection of the arrays
 */
public static Object[] intersection(List arrays, Class componentType) {
    if (componentType == null) {
        throw new IllegalArgumentException("componentType must be speciifed");
    }
    if (arrays == null) {
        return null;
    }

    Set intersectionSet = new HashSet();
    intersectionSet.addAll(Arrays.asList(((Object[]) arrays.get(0))));
    for (int i = 1; i < arrays.size(); i++) {
        Object[] array = (Object[]) arrays.get(i);
        for (int j = 0; j < array.length; j++) {
            if (!contains(intersectionSet, array[j])) {
                intersectionSet.remove(array[j]);
            }
        }
    }

    Object[] intersectionArray = (Object[]) ClassUtils.createArray(componentType, intersectionSet.size());
    return intersectionSet.toArray(intersectionArray);
}

From source file:com.dell.asm.asmcore.asmmanager.util.deployment.HostnameUtil.java

public static String replaceNumPattern(String hostnameTemplate, Set<String> allHostnames) {
    // we might already have the same hostname with auto-generated numbers. There is no way
    // to keep the counter updated, thus we have to check for dup every time we replace
    // ${num} with next gen number.
    String hostnameWithNumPattern = hostnameTemplate;

    int hostNameCounter = 0;
    while (hostnameWithNumPattern != null && hostNameCounter <= allHostnames.size()) {
        while (hostnameWithNumPattern.contains(NUM_PATTERN)) {
            hostNameCounter++;//from   w w w.  j  a va 2 s  .  c om
            hostnameWithNumPattern = hostnameWithNumPattern.replaceFirst(Pattern.quote(NUM_PATTERN),
                    String.valueOf(hostNameCounter));
        }

        if (!allHostnames.contains(hostnameWithNumPattern)) {
            hostnameTemplate = hostnameWithNumPattern;
            break;
        } else {
            // number pattern was already used, try again with next gen, reset the original name to get pattern back
            hostnameWithNumPattern = hostnameTemplate;
        }
    }
    return hostnameTemplate;
}

From source file:com.tuplejump.stargate.cassandra.CassandraUtils.java

public static Options getOptions(Properties mapping, ColumnFamilyStore baseCfs, String colName) {
    Properties primary = mapping;
    String defaultField = colName;
    Map<String, NumericConfig> numericFieldOptions = new HashMap<>();
    Map<String, FieldType> fieldDocValueTypes = new TreeMap<>();
    Map<String, FieldType> collectionFieldDocValueTypes = new TreeMap<>();

    Map<String, FieldType> fieldTypes = new TreeMap<>();
    Map<String, FieldType[]> collectionFieldTypes = new TreeMap<>();
    Map<String, AbstractType> validators = new TreeMap<>();
    Map<Integer, Pair<String, ByteBuffer>> clusteringKeysIndexed = new LinkedHashMap<>();
    Map<Integer, Pair<String, ByteBuffer>> partitionKeysIndexed = new LinkedHashMap<>();
    Map<String, Analyzer> perFieldAnalyzers;
    Set<String> indexedColumnNames;

    //getForRow all the fields options.
    indexedColumnNames = new TreeSet<>();
    indexedColumnNames.addAll(mapping.getFields().keySet());

    Set<String> added = new HashSet<>(indexedColumnNames.size());
    List<ColumnDefinition> partitionKeys = baseCfs.metadata.partitionKeyColumns();
    List<ColumnDefinition> clusteringKeys = baseCfs.metadata.clusteringKeyColumns();

    for (ColumnDefinition colDef : partitionKeys) {
        String columnName = CFDefinition.definitionType.getString(colDef.name);
        if (Options.logger.isDebugEnabled()) {
            Options.logger.debug("Partition key name is {} and index is {}", colName, colDef.componentIndex);
        }/*from w w  w.  jav  a2  s. co m*/
        validators.put(columnName, colDef.getValidator());
        if (indexedColumnNames.contains(columnName)) {
            int componentIndex = colDef.componentIndex == null ? 0 : colDef.componentIndex;
            partitionKeysIndexed.put(componentIndex, Pair.create(columnName, colDef.name));
            Properties properties = mapping.getFields().get(columnName.toLowerCase());
            addFieldType(columnName, colDef.getValidator(), properties, numericFieldOptions, fieldDocValueTypes,
                    collectionFieldDocValueTypes, fieldTypes, collectionFieldTypes);
            added.add(columnName.toLowerCase());
        }
    }

    for (ColumnDefinition colDef : clusteringKeys) {
        String columnName = CFDefinition.definitionType.getString(colDef.name);
        if (Options.logger.isDebugEnabled()) {
            Options.logger.debug("Clustering key name is {} and index is {}", colName,
                    colDef.componentIndex + 1);
        }
        validators.put(columnName, colDef.getValidator());
        if (indexedColumnNames.contains(columnName)) {
            clusteringKeysIndexed.put(colDef.componentIndex + 1, Pair.create(columnName, colDef.name));
            Properties properties = mapping.getFields().get(columnName.toLowerCase());
            addFieldType(columnName, colDef.getValidator(), properties, numericFieldOptions, fieldDocValueTypes,
                    collectionFieldDocValueTypes, fieldTypes, collectionFieldTypes);
            added.add(columnName.toLowerCase());
        }
    }

    for (String columnName : indexedColumnNames) {
        if (added.add(columnName.toLowerCase())) {
            Properties options = mapping.getFields().get(columnName);
            ColumnDefinition colDef = getColumnDefinition(baseCfs, columnName);
            if (colDef != null) {
                validators.put(columnName, colDef.getValidator());
                addFieldType(columnName, colDef.getValidator(), options, numericFieldOptions,
                        fieldDocValueTypes, collectionFieldDocValueTypes, fieldTypes, collectionFieldTypes);
            } else {
                throw new IllegalArgumentException(
                        String.format("Column Definition for %s not found", columnName));
            }
            if (options.getType() == Properties.Type.object) {
                mapping.getFields().putAll(options.getFields());
            }
        }

    }
    Set<ColumnDefinition> otherColumns = baseCfs.metadata.regularColumns();
    for (ColumnDefinition colDef : otherColumns) {
        String columnName = CFDefinition.definitionType.getString(colDef.name);
        validators.put(columnName, colDef.getValidator());
    }

    numericFieldOptions.putAll(primary.getDynamicNumericConfig());

    Analyzer defaultAnalyzer = mapping.getLuceneAnalyzer();
    perFieldAnalyzers = mapping.perFieldAnalyzers();
    Analyzer analyzer = new PerFieldAnalyzerWrapper(defaultAnalyzer, perFieldAnalyzers);
    Map<String, Properties.Type> types = new TreeMap<>();
    Set<String> nestedFields = new TreeSet<>();
    for (Map.Entry<String, AbstractType> entry : validators.entrySet()) {
        CQL3Type cql3Type = entry.getValue().asCQL3Type();
        AbstractType inner = getValueValidator(cql3Type.getType());
        if (cql3Type.isCollection()) {
            types.put(entry.getKey(), fromAbstractType(inner.asCQL3Type()));
            nestedFields.add(entry.getKey());
        } else {
            types.put(entry.getKey(), fromAbstractType(cql3Type));
        }

    }

    return new Options(primary, numericFieldOptions, fieldDocValueTypes, collectionFieldDocValueTypes,
            fieldTypes, collectionFieldTypes, types, nestedFields, clusteringKeysIndexed, partitionKeysIndexed,
            perFieldAnalyzers, indexedColumnNames, analyzer, defaultField);
}

From source file:freebase.api.FreebaseAPI.java

public static Set<Integer> getTopKActors(int minFilmPerActor) {
    final List<String> edges = Utils.readFileLineByLine(ACTOR_FILM_FILE, true);
    Map<String, Integer> film_per_actor_counts = new HashMap();
    for (String line : edges) {
        String split[] = line.split("\\t");
        String actor = split[0];//  w w w.ja  v  a 2 s .c  o m
        String film = split[1];
        Integer film_count = film_per_actor_counts.get(actor);
        if (film_count == null) {
            film_per_actor_counts.put(actor, 1);
        } else {
            film_per_actor_counts.put(actor, film_count + 1);
        }
    }
    Set<Integer> top_actors = new HashSet<>();
    for (String actor : film_per_actor_counts.keySet()) {
        if (film_per_actor_counts.get(actor) >= minFilmPerActor) {
            top_actors.add(Integer.parseInt(actor));
        }
    }
    System.out.println("Top-Actors# :" + top_actors.size());
    return top_actors;
}

From source file:com.taobao.tddl.interact.rule.VirtualTable.java

/**
 * #id,1,32|512_64#//from  w ww .ja  v a  2  s  . c o  m
 */
@SuppressWarnings("rawtypes")
private static Map<String/**/, Set<Object>/**/> getEnumerates(Rule rule) {
    Set<AdvancedParameter> params = cast(rule.getRuleColumnSet());
    Map<String/**/, Set<Object>/**/> enumerates = new HashMap<String, Set<Object>>(params.size());
    for (AdvancedParameter ap : params) {
        enumerates.put(ap.key, ap.enumerateRange());
    }
    return enumerates;
}

From source file:com.struts2ext.json.JSONUtil.java

static List<Pattern> processIncludePatterns(Set<String> includePatterns, String type,
        Map<String, Map<String, String>> includePatternData) {
    if (includePatterns != null) {
        List<Pattern> results = new ArrayList<Pattern>(includePatterns.size());
        Map<String, String> existingPatterns = new HashMap<String, String>();
        for (String pattern : includePatterns) {
            processPattern(results, existingPatterns, pattern, type, includePatternData);
        }/* w  w w .ja  v  a 2s.c o m*/
        return results;
    } else {
        return null;
    }
}

From source file:io.cloudslang.content.amazon.utils.InputsUtil.java

private static void validateArrayAgainstDuplicateElements(String[] toBeValidated, String inputString,
        String delimiter, String inputName) {
    if (toBeValidated != null && isNotBlank(inputString)) {
        Set<String> stringSet = getStringsSet(inputString, delimiter);
        if (stringSet != null && toBeValidated.length != stringSet.size()) {
            throw new RuntimeException("The value provided for: " + inputName
                    + " input contain duplicate elements. " + "Please provide unique elements!");
        }/*  w ww  .j  a  v  a  2  s.co m*/
    }
}

From source file:com.reactivetechnologies.platform.utils.EntityFinder.java

/**
 * /*from  w w w  .ja  v  a2 s. c o  m*/
 * @param basePkg
 * @return
 * @throws ClassNotFoundException
 */
public static Collection<Class<?>> findMapEntityClasses(String basePkg) throws ClassNotFoundException {
    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(
            false);
    provider.addIncludeFilter(new TypeFilter() {

        @Override
        public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
                throws IOException {
            AnnotationMetadata aMeta = metadataReader.getAnnotationMetadata();
            return aMeta.hasAnnotation(HzMapConfig.class.getName());
        }
    });
    //consider the finder class to be in the root package
    Set<BeanDefinition> beans = null;
    try {
        beans = provider.findCandidateComponents(StringUtils.hasText(basePkg) ? basePkg
                : EntityFinder.class.getName().substring(0, EntityFinder.class.getName().lastIndexOf(".")));
    } catch (Exception e) {
        throw new IllegalArgumentException("Unable to scan for entities under base package", e);
    }

    Set<Class<?>> classes = new HashSet<>();
    if (beans != null && !beans.isEmpty()) {
        classes = new HashSet<>(beans.size());
        for (BeanDefinition bd : beans) {
            classes.add(Class.forName(bd.getBeanClassName()));
        }
    } else {
        log.warn(">> Did not find any key value entities under the given base scan package [" + basePkg + "]");
    }
    return classes;

}