Tabnine Logo
List.forEach
Code IndexAdd Tabnine to your IDE (free)

How to use
forEach
method
in
java.util.List

Best Java code snippets using java.util.List.forEach (Showing top 20 results out of 46,521)

Refine searchRefine arrow

  • List.add
  • List.size
  • List.isEmpty
  • Map.put
  • List.stream
  • Stream.collect
  • Stream.map
  • Stream.filter
  • Collectors.toList
  • List.get
  • Map.get
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"));
}
origin: spring-projects/spring-framework

/**
 * {@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;
}
origin: apache/flink

@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;
}
origin: spring-projects/spring-framework

@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;
}
origin: spring-projects/spring-framework

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);
}
origin: apache/hbase

public static List<byte[]> getUtf8ByteArrays(List<String> strings) {
 if (CollectionUtils.isEmpty(strings)) {
  return Collections.emptyList();
 }
 List<byte[]> byteArrays = new ArrayList<>(strings.size());
 strings.forEach(s -> byteArrays.add(Bytes.toBytes(s)));
 return byteArrays;
}
origin: jenkinsci/jenkins

/**
 * 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());
}

origin: ctripcorp/apollo

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);
 }
}
origin: galenframework/galen

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;
}
origin: prestodb/presto

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)));
origin: apache/incubator-dubbo

public void init() {
  if (!isValid()) {
    return;
  }
  tags.forEach(tag -> {
    tagnameToAddresses.put(tag.getName(), tag.getAddresses());
    tag.getAddresses().forEach(addr -> {
      List<String> tagNames = addressToTagnames.computeIfAbsent(addr, k -> new ArrayList<>());
      tagNames.add(tag.getName());
    });
  });
}
origin: lettuce-io/lettuce-core

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;
}
origin: Graylog2/graylog2-server

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;
}
origin: MovingBlocks/Terasology

@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);
}
origin: apache/incubator-druid

private static Map<String, AggregatorFactory> getAggregatorsMap(List<AggregatorFactory> aggregatorSpecs)
{
 Map<String, AggregatorFactory> map = new HashMap<>(aggregatorSpecs.size());
 aggregatorSpecs.forEach(v -> map.put(v.getName(), v));
 return map;
}
origin: lettuce-io/lettuce-core

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));
}
origin: thinkaurelius/titan

@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();
  }
}
origin: prestodb/presto

@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);
}
origin: spring-projects/spring-framework

  @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();
  }
}
origin: prestodb/presto

  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);
  }
}
java.utilListforEach

Popular methods of List

  • add
  • size
    Returns the number of elements in this List.
  • get
    Returns the element at the specified location in this List.
  • isEmpty
    Returns whether this List contains no elements.
  • addAll
  • toArray
    Returns an array containing all elements contained in this List. If the specified array is large eno
  • contains
    Tests whether this List contains the specified object.
  • remove
    Removes the first occurrence of the specified object from this List.
  • iterator
    Returns an iterator on the elements of this List. The elements are iterated in the same order as the
  • clear
  • stream
  • set
    Replaces the element at the specified position in this list with the specified element (optional ope
  • stream,
  • set,
  • subList,
  • indexOf,
  • equals,
  • hashCode,
  • removeAll,
  • listIterator,
  • sort

Popular in Java

  • Making http requests using okhttp
  • scheduleAtFixedRate (Timer)
  • startActivity (Activity)
  • getApplicationContext (Context)
  • SecureRandom (java.security)
    This class generates cryptographically secure pseudo-random numbers. It is best to invoke SecureRand
  • Timestamp (java.sql)
    A Java representation of the SQL TIMESTAMP type. It provides the capability of representing the SQL
  • LinkedHashMap (java.util)
    LinkedHashMap is an implementation of Map that guarantees iteration order. All optional operations a
  • Locale (java.util)
    Locale represents a language/country/variant combination. Locales are used to alter the presentatio
  • SortedMap (java.util)
    A map that has its keys ordered. The sorting is according to either the natural ordering of its keys
  • SSLHandshakeException (javax.net.ssl)
    The exception that is thrown when a handshake could not be completed successfully.
  • Top Sublime Text plugins
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now