canonical example by Tabnine
private void mappingWordsLength(List<String> wordsList) { Map<Integer, Set<String>> mapping = new HashMap<>(); for (String word : wordsList) { mapping.computeIfAbsent(word.length(), HashSet::new).add(word); } List<Integer> lengths = new LinkedList<>(mapping.keySet()); Collections.sort(lengths); lengths.forEach(n -> System.out.println(mapping.get(n).size() + " words with " + n + " chars")); }
/** * {@inheritDoc} * <p>This implementation creates a single {@link DefaultDataBuffer} * to contain the data in {@code dataBuffers}. */ @Override public DefaultDataBuffer join(List<? extends DataBuffer> dataBuffers) { Assert.notEmpty(dataBuffers, "DataBuffer List must not be empty"); int capacity = dataBuffers.stream().mapToInt(DataBuffer::readableByteCount).sum(); DefaultDataBuffer result = allocateBuffer(capacity); dataBuffers.forEach(result::write); dataBuffers.forEach(DataBufferUtils::release); return result; }
@SuppressWarnings("unchecked") public TtlVerificationContext( int key, @Nonnull String verifierId, @Nonnull List<ValueWithTs<?>> prevUpdates, @Nonnull TtlUpdateContext<?, ?> updateContext) { this.key = key; this.verifierId = verifierId; this.prevUpdates = new ArrayList<>(); prevUpdates.forEach(pu -> this.prevUpdates.add((ValueWithTs<UV>) pu)); this.updateContext = (TtlUpdateContext<UV, GV>) updateContext; }
@Override public Map<String, String> toSingleValueMap() { Map<String, String> singleValueMap = new LinkedHashMap<>(this.headers.size()); this.headers.entries() .forEach(entry -> { if (!singleValueMap.containsKey(entry.getKey())) { singleValueMap.put(entry.getKey(), entry.getValue()); } }); return singleValueMap; }
private Mono<Void> invokeModelAttributeMethods(BindingContext bindingContext, List<InvocableHandlerMethod> modelMethods, ServerWebExchange exchange) { List<Mono<HandlerResult>> resultList = new ArrayList<>(); modelMethods.forEach(invocable -> resultList.add(invocable.invoke(exchange, bindingContext))); return Mono .zip(resultList, objectArray -> Arrays.stream(objectArray) .map(object -> handleResult(((HandlerResult) object), bindingContext)) .collect(Collectors.toList())) .flatMap(Mono::when); }
/** * In case of duplicate entries, we keep only the last updated element */ private void keepLastUpdatedUnique() { Map<String, SingleTokenStats> temp = new HashMap<>(); this.tokenStats.forEach(candidate -> { SingleTokenStats current = temp.get(candidate.tokenUuid); if (current == null) { temp.put(candidate.tokenUuid, candidate); } else { int comparison = SingleTokenStats.COMP_BY_LAST_USE_THEN_COUNTER.compare(current, candidate); if (comparison < 0) { // candidate was updated more recently (or has a bigger counter in case of perfectly equivalent dates) temp.put(candidate.tokenUuid, candidate); } } }); this.tokenStats = new ArrayList<>(temp.values()); }
private void loadReleaseMessages(long startId) { boolean hasMore = true; while (hasMore && !Thread.currentThread().isInterrupted()) { //current batch is 500 List<ReleaseMessage> releaseMessages = releaseMessageRepository .findFirst500ByIdGreaterThanOrderByIdAsc(startId); if (CollectionUtils.isEmpty(releaseMessages)) { break; } releaseMessages.forEach(this::mergeReleaseMessage); int scanned = releaseMessages.size(); startId = releaseMessages.get(scanned - 1).getId(); hasMore = scanned == 500; logger.info("Loaded {} release messages with startId {}", scanned, startId); } }
private Map<String, List<String>> groupBySpecs() { Map<String, List<String>> specsMap = new HashMap<>(); objectSpecs.forEach(object -> object.getSpecs().forEach(spec -> { List<String> objectsPerSpec = specsMap.get(spec.getStatement()); if (objectsPerSpec == null) { objectsPerSpec = new LinkedList<>(); specsMap.put(spec.getStatement(), objectsPerSpec); } if (!objectsPerSpec.contains(object.getObjectName())) { objectsPerSpec.add(object.getObjectName()); } }) ); return specsMap; }
for (int i = 0; i < source.getSources().size(); i++) { Symbol symbol = context.getSymbolAllocator().newSymbol(translatedExpression, type); assignments.put(symbol, translatedExpression); projectSymbolMapping.put(entry.getKey(), symbol); outputSources.add(new ProjectNode(context.getIdAllocator().getNextId(), source.getSources().get(i), assignments.build())); outputLayout.forEach(symbol -> mappings.put(symbol, projectSymbolMapping.get(symbol)));
private Voted<RedisCodec<?, ?>> voteForTypeMajority(CommandMethod commandMethod) { List<Voted<RedisCodec<?, ?>>> votes = codecs.stream().map(redisCodec -> new Voted<RedisCodec<?, ?>>(redisCodec, 0)) .collect(Collectors.toList()); commandMethod.getParameters().getBindableParameters().forEach(parameter -> { vote(votes, parameter); }); Collections.sort(votes); if (votes.isEmpty()) { return null; } Voted<RedisCodec<?, ?>> voted = votes.get(votes.size() - 1); if (voted.votes == 0) { return null; } return voted; }
public List<String> analyze(String toAnalyze, String index, String analyzer) throws IOException { final Analyze analyze = new Analyze.Builder().index(index).analyzer(analyzer).text(toAnalyze).build(); final JestResult result = client.execute(analyze); @SuppressWarnings("unchecked") final List<Map<String, Object>> tokens = (List<Map<String, Object>>) result.getValue("tokens"); final List<String> terms = new ArrayList<>(tokens.size()); tokens.forEach(token -> terms.add((String)token.get("token"))); return terms; }
@Override public void update(float delta) { if (!isCreated) { isCreated = true; for (int i = 0; i < buttons.size(); i++) { UIButton button = buttons.get(i); listeners.add(widget -> currentTab = buttons.indexOf(widget)); button.subscribe(listeners.get(listeners.size() - 1)); buttonLayout.addWidget(button, null); buttons.set(i, button); } } buttons.forEach(b -> b.setActive(currentTab == buttons.indexOf(b))); super.update(delta); }
private <T> Flux<T> pipeliningWithMap(Map<K, V> map, Function<Map<K, V>, Flux<T>> function, Function<Flux<T>, Flux<T>> resultFunction) { Map<Integer, List<K>> partitioned = SlotHash.partition(codec, map.keySet()); if (partitioned.size() < 2) { return function.apply(map); } List<Flux<T>> publishers = partitioned.values().stream().map(ks -> { Map<K, V> op = new HashMap<>(); ks.forEach(k -> op.put(k, map.get(k))); return function.apply(op); }).collect(Collectors.toList()); return resultFunction.apply(Flux.merge(publishers)); }
@SuppressWarnings("deprecation") private void initialize() { assert !initialized; initialized = true; assert getReturnType().forProperties() || (orders.isEmpty() && hasContainers.isEmpty()); if (!starts.hasNext()) throw FastNoSuchElementException.instance(); List<Traverser.Admin<Element>> elements = new ArrayList<>(); starts.forEachRemaining(v -> elements.add(v)); starts.add(elements.iterator()); assert elements.size() > 0; useMultiQuery = useMultiQuery && elements.stream().noneMatch(e -> !(e.get() instanceof Vertex)); if (useMultiQuery) { TitanMultiVertexQuery mquery = TitanTraversalUtil.getTx(traversal).multiQuery(); elements.forEach(e -> mquery.addVertex((Vertex) e.get())); makeQuery(mquery); multiQueryResults = mquery.properties(); } }
@Override public void enqueue(int partitionNumber, List<SerializedPage> pages) { requireNonNull(pages, "pages is null"); // ignore pages after "no more pages" is set // this can happen with a limit query if (!state.get().canAddPages()) { return; } // reserve memory long bytesAdded = pages.stream().mapToLong(SerializedPage::getRetainedSizeInBytes).sum(); memoryManager.updateMemoryUsage(bytesAdded); // update stats long rowCount = pages.stream().mapToLong(SerializedPage::getPositionCount).sum(); totalRowsAdded.addAndGet(rowCount); totalPagesAdded.addAndGet(pages.size()); // create page reference counts with an initial single reference List<SerializedPageReference> serializedPageReferences = pages.stream() .map(bufferedPage -> new SerializedPageReference(bufferedPage, 1, () -> memoryManager.updateMemoryUsage(-bufferedPage.getRetainedSizeInBytes()))) .collect(toImmutableList()); // add pages to the buffer (this will increase the reference count by one) partitions.get(partitionNumber).enqueuePages(serializedPageReferences); // drop the initial reference serializedPageReferences.forEach(SerializedPageReference::dereferencePage); }
@Override public boolean isValid(Object value, ConstraintValidatorContext context) { List<Field> fieldsErros = new ArrayList<>(); Arrays.asList(value.getClass().getDeclaredFields()).forEach(f -> { f.setAccessible(true); try { if (!f.getName().equals(ID) && f.get(value) == null) { fieldsErros.add(f); context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate()) .addPropertyNode(f.getName()) .addConstraintViolation(); } } catch (IllegalAccessException ex) { throw new IllegalStateException(ex); } }); return fieldsErros.isEmpty(); } }
private JoinGraph replacementGraph(PlanNode oldNode, PlanNode newNode, Context context) { // TODO optimize when idea is generally approved List<Symbol> symbols = context.symbolSources.entrySet().stream() .filter(entry -> entry.getValue() == oldNode) .map(Map.Entry::getKey) .collect(toImmutableList()); symbols.forEach(symbol -> context.symbolSources.put(symbol, newNode)); return new JoinGraph(newNode); } }