Example usage for java.util Collections frequency

List of usage examples for java.util Collections frequency

Introduction

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

Prototype

public static int frequency(Collection<?> c, Object o) 

Source Link

Document

Returns the number of elements in the specified collection equal to the specified object.

Usage

From source file:net.sf.jabref.logic.util.io.FileUtil.java

/**
 * Creates the minimal unique path substring for each file among multiple file paths.
 *
 * @param paths the file paths//  w w  w. j a  v  a 2s . co m
 * @return the minimal unique path substring for each file path
 */
public static List<String> uniquePathSubstrings(List<String> paths) {
    List<Stack<String>> stackList = new ArrayList<>(paths.size());
    // prepare data structures
    for (String path : paths) {
        List<String> directories = Arrays.asList(path.split(Pattern.quote(File.separator)));
        Stack<String> stack = new Stack<>();
        stack.addAll(directories);
        stackList.add(stack);
    }

    List<String> pathSubstrings = new ArrayList<>(Collections.nCopies(paths.size(), ""));

    // compute shortest folder substrings
    while (!stackList.stream().allMatch(Vector::isEmpty)) {
        for (int i = 0; i < stackList.size(); i++) {
            String tempString = pathSubstrings.get(i);

            if (tempString.isEmpty() && !stackList.get(i).isEmpty()) {
                pathSubstrings.set(i, stackList.get(i).pop());
            } else if (!stackList.get(i).isEmpty()) {
                pathSubstrings.set(i, stackList.get(i).pop() + File.separator + tempString);
            }
        }

        for (int i = 0; i < stackList.size(); i++) {
            String tempString = pathSubstrings.get(i);

            if (Collections.frequency(pathSubstrings, tempString) == 1) {
                stackList.get(i).clear();
            }
        }
    }
    return pathSubstrings;
}

From source file:se.uu.it.cs.recsys.ruleminer.datastructure.builder.FPTreeHeaderTableBuilder.java

/**
 *
 * @param idAndCount item id and count/*from   ww  w  .j av  a 2  s.  c om*/
 * @param threshold, min support
 * @return non-null HeaderTableItem if the input contains id meets threshold
 * requirement; otherwise null.
 */
public static List<HeaderTableItem> build(Map<Integer, Integer> idAndCount, Integer threshold) {

    List<HeaderTableItem> instance = new ArrayList<>();

    Map<Integer, Integer> filteredIdAndCount = Util.filter(idAndCount, threshold);

    if (filteredIdAndCount.isEmpty()) {
        LOGGER.debug("Empty map after filtering. Empty list will be returned. Source: {}", idAndCount);
        return instance;
    }

    List<Integer> countList = new ArrayList<>(filteredIdAndCount.values());
    Collections.sort(countList);
    Collections.reverse(countList);// now the count is in DESC order

    for (int i = 1; i <= filteredIdAndCount.size(); i++) {
        instance.add(new HeaderTableItem()); // in order to call list.set(idx,elem)
    }

    Map<Integer, Set<Integer>> forIdsHavingSameCount = new HashMap<>();//different ids may have same count

    filteredIdAndCount.entrySet().forEach((entry) -> {
        Integer courseId = entry.getKey();
        Integer count = entry.getValue();

        Integer countFrequence = Collections.frequency(countList, count);

        if (countFrequence == 1) {
            Integer countIdx = countList.indexOf(count);
            instance.set(countIdx, new HeaderTableItem(new Item(courseId, count)));
        } else {
            // different ids have same count

            if (!forIdsHavingSameCount.containsKey(count)) {
                forIdsHavingSameCount.put(count, Util.findDuplicatesIndexes(countList, count));
            }

            Iterator<Integer> itr = forIdsHavingSameCount.get(count).iterator();
            Integer idx = itr.next();
            itr.remove();

            instance.set(idx, new HeaderTableItem(new Item(courseId, count)));
        }

    });

    //        LOGGER.debug("Final built header table: {}",
    //                instance.stream()
    //                .map(headerItem -> headerItem.getItem()).collect(Collectors.toList()));

    return instance;
}

From source file:org.springframework.batch.repeat.support.TaskExecutorRepeatTemplateBulkAsynchronousTests.java

@Test
public void testThrottleLimit() throws Exception {

    template.iterate(callback);/*w w  w . j  a v a 2  s . c om*/
    int frequency = Collections.frequency(items, "null");
    // System.err.println(items);
    // System.err.println("Frequency: " + frequency);
    assertEquals(total, items.size() - frequency);
    assertTrue(frequency > 1);
    assertTrue(frequency <= throttleLimit + 1);

}

From source file:org.springframework.batch.repeat.support.TaskExecutorRepeatTemplateBulkAsynchronousTests.java

@Test
public void testThrottleLimitEarlyFinish() throws Exception {

    early = 2;/*from   w  w w . j  av a 2  s  . co  m*/

    template.iterate(callback);
    int frequency = Collections.frequency(items, "null");
    // System.err.println("Frequency: " + frequency);
    // System.err.println("Items: " + items);
    assertEquals(total, items.size() - frequency);
    assertTrue(frequency > 1);
    assertTrue(frequency <= throttleLimit + 1);

}

From source file:com.google.walkaround.wave.server.servlet.UndercurrentHandler.java

private JSONObject clientVarString(@Nullable LiveClientVars liveClientVars,
        @Nullable StaticClientVars staticClientVars, @Nullable ErrorVars errorVars) {
    Preconditions/*ww  w.  j  ava  2 s.  c o m*/
            .checkArgument(
                    Collections.frequency(ImmutableList.of(liveClientVars != null, staticClientVars != null,
                            errorVars != null), true) == 1,
                    "%s/%s/%s", liveClientVars, staticClientVars, errorVars);
    ClientVarsGsonImpl clientVars = new ClientVarsGsonImpl();
    if (liveClientVars != null) {
        clientVars.setLiveClientVars(liveClientVars);
    } else if (staticClientVars != null) {
        clientVars.setStaticClientVars(staticClientVars);
    } else {
        clientVars.setErrorVars(errorVars);
    }
    String jsonString = GsonProto.toJson(clientVars);
    try {
        // TODO(ohler): Find a way to embed a GSON-generated JSON literal in GXP
        // without serializing and re-parsing to org.json.JSONObject.  Perhaps
        // through JavascriptClosure?
        return new JSONObject(jsonString);
    } catch (JSONException e) {
        throw new RuntimeException("org.json failed to parse GSON's output: " + jsonString, e);
    }
}

From source file:org.wildfly.security.tool.Command.java

/**
 * Alerts if any of the command line options used are duplicated
 * @param cmdLine the command line options used when invoking the command, after parsing
 *///  ww w  .  j a v a  2s.  co  m
public void printDuplicatesWarning(CommandLine cmdLine) {
    List<Option> optionsList = new ArrayList<>(Arrays.asList(cmdLine.getOptions()));
    Set<Option> duplicatesSet = new HashSet<>();
    for (Option option : cmdLine.getOptions()) {
        if (Collections.frequency(optionsList, option) > 1) {
            duplicatesSet.add(option);
        }
    }

    for (Option option : duplicatesSet) {
        System.out.println(ElytronToolMessages.msg.duplicateOptionSpecified(option.getLongOpt()));
    }
}

From source file:org.jsweet.input.typescriptdef.visitor.TypeMerger.java

@Override
public void visitTypeDeclaration(TypeDeclaration typeDeclaration) {
    if (typeDeclaration.isExternal()) {
        return;/*w w w  .  j av a2 s .co m*/
    }
    String modName = getCurrentModuleName();
    String libModule = context.getLibModule(modName);
    if (typeDeclaration.getName() != null) {
        if (isCoreMergeCandidate(modName)) {
            TypeDeclaration targetType = null;
            targetType = context.getTypeDeclaration(
                    JSweetDefTranslatorConfig.LANG_PACKAGE + "." + typeDeclaration.getName());
            if (targetType == null) {
                targetType = context.getTypeDeclaration(
                        JSweetDefTranslatorConfig.DOM_PACKAGE + "." + typeDeclaration.getName());
            }
            boolean coreTarget = targetType != null;
            if (targetType == null) {
                // this is for cross lib merge (will not be applied on a
                // per-lib
                // generation strategy)
                if (libModule != null) {
                    String libRelativePath = context.getLibRelativePath(modName);

                    List<String> dependencies = context.dependencyGraph.getDestinationElements(libModule);
                    if (dependencies == null) {
                        context.reportError("cannot find dependency for module " + libModule + " (type "
                                + typeDeclaration + "): check dependecy graph initialization", (Token) null);
                    } else {
                        for (String targetLibModule : dependencies) {
                            if (targetLibModule == null) {
                                continue;
                            }
                            if (modName.equals(libRelativePath)) {
                                targetType = context
                                        .getTypeDeclaration(targetLibModule + "." + typeDeclaration.getName());
                            } else {
                                targetType = context.getTypeDeclaration(targetLibModule + "." + libRelativePath
                                        + "." + typeDeclaration.getName());
                            }
                            if (targetType != null) {
                                break;
                            }
                        }
                    }
                }
            }

            if (targetType == typeDeclaration) {
                return;
            }

            if (targetType != null) {
                if (libModule == null && coreTarget || libModule != null
                        && libModule.equals(context.getLibModule(context.getTypeName(targetType)))) {
                    mergeTypes(typeDeclaration, targetType);
                } else {
                    logger.debug("add @Mixin annotation for cross-lib type: " + modName + "."
                            + typeDeclaration.getName() + "@" + typeDeclaration.getLocation() + " ==> "
                            + context.getTypeName(targetType) + "@" + targetType.getLocation());
                    typeDeclaration.addStringAnnotation(JSweetDefTranslatorConfig.ANNOTATION_MIXIN + "(target="
                            + context.getTypeName(targetType) + ".class)");
                    typeDeclaration.setSuperTypes(new TypeReference[] {
                            new TypeReference(null, context.getTypeName(targetType), null) });
                    context.resiterMixin(libModule, typeDeclaration);
                    // TODO: redirect references
                }
            }
        } else {
            if (Collections.frequency(context.getTypeNames().values(),
                    context.getTypeName(typeDeclaration)) > 1) {
                if (!"interface".equals(typeDeclaration.getOriginalKind())) {
                    context.reportWarning("duplicate type is not an interface: " + typeDeclaration + " at "
                            + typeDeclaration.getLocation());
                    return;
                }
                for (Entry<TypeDeclaration, String> e : new HashSet<>(context.getTypeNames().entrySet())) {
                    if (e.getKey() == typeDeclaration
                            || !e.getValue().equals(context.getTypeName(typeDeclaration))) {
                        continue;
                    }
                    if (!"interface".equals(e.getKey().getOriginalKind())) {
                        context.reportWarning("duplicate type is not an interface: " + e.getKey() + " at "
                                + e.getKey().getLocation());
                        return;
                    }
                    mergeTypes(e.getKey(), typeDeclaration);
                }
            }
        }
    }

}

From source file:org.springframework.batch.repeat.support.TaskExecutorRepeatTemplateBulkAsynchronousTests.java

@Test
public void testThrottleLimitEarlyFinishThreadStarvation() throws Exception {

    early = 2;//from  ww  w  .  j av a  2s .c o  m
    ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
    // Set the concurrency limit below the throttle limit for possible
    // starvation condition
    taskExecutor.setMaxPoolSize(20);
    taskExecutor.setCorePoolSize(10);
    taskExecutor.setQueueCapacity(0);
    // This is the most sensible setting, otherwise the bookkeeping in
    // ResultHolderResultQueue gets out of whack when tasks are aborted.
    taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
    taskExecutor.afterPropertiesSet();
    template.setTaskExecutor(taskExecutor);

    template.iterate(callback);
    int frequency = Collections.frequency(items, "null");
    // System.err.println("Frequency: " + frequency);
    // System.err.println("Items: " + items);
    // Extra tasks will be submitted before the termination is detected
    assertEquals(total, items.size() - frequency);
    assertTrue(frequency <= throttleLimit + 1);

    taskExecutor.destroy();

}

From source file:org.springframework.batch.repeat.support.TaskExecutorRepeatTemplateBulkAsynchronousTests.java

@Test
public void testThrottleLimitEarlyFinishOneThread() throws Exception {

    early = 4;//from  w ww  .  ja  v  a2  s  .  c  o m
    SimpleAsyncTaskExecutor taskExecutor = new SimpleAsyncTaskExecutor();
    taskExecutor.setConcurrencyLimit(1);

    // This is kind of slow with only one thread, so reduce size:
    throttleLimit = 10;
    total = 20;

    template.setThrottleLimit(throttleLimit);
    template.setTaskExecutor(taskExecutor);

    template.iterate(callback);
    int frequency = Collections.frequency(items, "null");
    // System.err.println("Frequency: " + frequency);
    // System.err.println("Items: " + items);
    assertEquals(total, items.size() - frequency);
    assertTrue(frequency <= throttleLimit + 1);

}

From source file:sia.airblio.servlets.MappemondeRequest.java

private void getMaterielsSite(Session session) {
    Query query = session.createQuery("from SiteStockage");
    List<SiteStockage> sites = query.list();
    for (SiteStockage site : sites) {
        String content = "<h3>" + site.getNom() + "</h3><p>";
        Iterator it = site.getMateriauxStockes().iterator();
        List<String> matUniq = new ArrayList<>();
        List<String> matAll = new ArrayList<>();
        while (it.hasNext()) {
            Materiel materiel = (Materiel) it.next();
            matAll.add(materiel.getNom());
        }//from   w  ww .j  ava 2 s .c  o  m
        it = matAll.iterator();
        while (it.hasNext()) {
            String nomMat = (String) it.next();
            if (!matUniq.contains(nomMat)) {
                matUniq.add(nomMat);
                content += nomMat + ": " + Collections.frequency(matAll, nomMat);
                content += (it.hasNext() ? "<br />" : "");
            }
        }
        content += "</p>";
        JSONObject jsonSites = new JSONObject();
        jsonSites.put("nom", site.getNom());
        jsonSites.put("latitude", site.getLatitude());
        jsonSites.put("longitude", site.getLongitude());
        jsonSites.put("content", content);
        json.put(site.getId(), jsonSites);
    }
}