java.util.stream.Stream.limit()方法的使用及代码示例

x33g5p2x  于2022-01-16 转载在 其他  
字(8.3k)|赞(0)|评价(0)|浏览(369)

本文整理了Java中java.util.stream.Stream.limit()方法的一些代码示例,展示了Stream.limit()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Stream.limit()方法的具体详情如下:
包路径:java.util.stream.Stream
类名称:Stream
方法名:limit

Stream.limit介绍

[英]Returns a stream consisting of the elements of this stream, truncated to be no longer than maxSize in length.

This is a short-circuiting stateful intermediate operation.
[中]返回由此流的元素组成的流,该流被截断为长度不超过maxSize。
这是一个short-circuiting stateful intermediate operation

代码示例

canonical example by Tabnine

public List<Integer> findDivisors(int number) {
 return Stream.iterate(1, k -> ++k)
   .limit(number)
   .filter(k -> number % k == 0)
   .collect(Collectors.toList());
}

canonical example by Tabnine

public void printFibonacciSequence(int length) {
 System.out.println(
   Stream.iterate(new long[] {0, 1}, pair -> new long[] {pair[1], pair[0] + pair[1]})
     .limit(length)
     .map(pair -> Long.toString(pair[1]))
     .collect(Collectors.joining(", ")));
}

代码示例来源:origin: yu199195/hmily

private List<HmilyCompensationVO> findByPage(final File[] files, final int start, final int pageSize) {
  if (files != null && files.length > 0) {
    return Arrays.stream(files).skip(start).limit(pageSize)
        .map(this::readTransaction)
        .collect(Collectors.toList());
  }
  return null;
}

代码示例来源:origin: shekhargulati/99-problems

public static <T> T kthStream(final List<T> list, final int k) {
  return list.stream().limit(k + 1).collect(Collectors.toCollection(LinkedList::new)).getLast();
}

代码示例来源:origin: Vedenin/useful-java-links

private static void testLimit() {
  System.out.println();
  System.out.println("Test limit start");
  Collection<String> collection = Arrays.asList("a1", "a2", "a3", "a1");
  // Get the first two elements
  List<String> limit = collection.stream().limit(2).collect(Collectors.toList());
  System.out.println("limit = " + limit); // print  limit = [a1, a2]
  // Get two elements from second element
  List<String> fromTo = collection.stream().skip(1).limit(2).collect(Collectors.toList());
  System.out.println("fromTo = " + fromTo); // print  fromTo = [a2, a3]
  // Get the last element
  String last = collection.stream().skip(collection.size() - 1).findAny().orElse("1");
  System.out.println("last = " + last ); // print  last = a1
}

代码示例来源:origin: ethereum/ethereumj

private String strSample(Collection<byte[]> hashes) {
  String sample = hashes.stream().limit(3)
      .map(HashUtil::shortHash).collect(Collectors.joining(", "));
  if (hashes.size() > 3) {
    sample += ", ... (" + hashes.size() + " total)";
  }
  return sample;
}

代码示例来源:origin: yu199195/hmily

private List<HmilyCompensationVO> findByPage(final Set<byte[]> keys, final int start, final int pageSize) {
  return keys.parallelStream()
      .skip(start)
      .limit(pageSize)
      .map(this::buildVOByKey)
      .filter(Objects::nonNull)
      .collect(Collectors.toList());
}

代码示例来源:origin: apache/ignite

/** This method generates "random double, integer" pairs, sort them, gets first "testSize" elements and returns appropriate indices */
@NotNull private TreeSet<Integer> getSortedIndices(int datasetSize, int testSize) {
  Random rnd = new Random();
  TreeMap<Double, Integer> randomIdxPairs = new TreeMap<>();
  for (int i = 0; i < datasetSize; i++)
    randomIdxPairs.put(rnd.nextDouble(), i);
  final TreeMap<Double, Integer> testIdxPairs = randomIdxPairs.entrySet().stream()
    .limit(testSize)
    .collect(TreeMap::new, (m, e) -> m.put(e.getKey(), e.getValue()), Map::putAll);
  return new TreeSet<>(testIdxPairs.values());
}

代码示例来源:origin: JanusGraph/janusgraph

public static <O> Iterable<O> limitedIterable(final Iterable<O> iterable, final int limit) {
  return StreamSupport.stream(iterable.spliterator(), false).limit(limit).collect(Collectors.toList());
}

代码示例来源:origin: apache/ignite

/**
 * Convert first N values from stream to map.
 *
 * @param datasetSize Dataset size.
 * @return Map of vectors and labels.
 */
public default Map<Vector, Double> asMap(int datasetSize) {
  return labeled().limit(datasetSize)
    .collect(Collectors.toMap(DatasetRow::features, LabeledVector::label));
}

代码示例来源:origin: yu199195/Raincat

private List<TransactionRecoverVO> findByPage(final File[] files, final int start, final int pageSize) {
  if (files != null && files.length > 0) {
    return Arrays.stream(files).skip(start).limit(pageSize)
        .map(this::readTransaction)
        .collect(Collectors.toList());
  }
  return null;
}

代码示例来源:origin: prestodb/presto

private static List<Node> createArbitraryBucketToNode(List<Node> nodes, int bucketCount)
{
  return cyclingShuffledStream(nodes)
      .limit(bucketCount)
      .collect(toImmutableList());
}

代码示例来源:origin: yu199195/myth

private List<LogVO> findByPage(final File[] files, final int start, final int pageSize) {
  if (files != null && files.length > 0) {
    return Arrays.stream(files).skip(start).limit(pageSize)
        .map(this::readTransaction)
        .collect(Collectors.toList());
  }
  return null;
}

代码示例来源:origin: apache/incubator-druid

@VisibleForTesting
static String[] getFrequentLocations(final Stream<String> locations)
{
 final Map<String, Long> locationCountMap = locations.collect(
   Collectors.groupingBy(location -> location, Collectors.counting())
 );
 final Comparator<Map.Entry<String, Long>> valueComparator =
   Map.Entry.comparingByValue(Comparator.reverseOrder());
 final Comparator<Map.Entry<String, Long>> keyComparator =
   Map.Entry.comparingByKey();
 return locationCountMap
   .entrySet().stream()
   .sorted(valueComparator.thenComparing(keyComparator))
   .limit(3)
   .map(Map.Entry::getKey)
   .toArray(String[]::new);
}

代码示例来源:origin: yu199195/Raincat

private List<TransactionRecoverVO> findByPage(final Set<byte[]> keys, final int start, final int pageSize) {
  return keys.parallelStream()
      .skip(start).limit(pageSize)
      .map(this::buildVOByKey)
      .filter(Objects::nonNull).collect(Collectors.toList());
}

代码示例来源:origin: SonarSource/sonarqube

private static String computeMessage(String dataWording, Set<Component> filesWithErrors) {
 if (filesWithErrors.size() == 1) {
  Component file = filesWithErrors.iterator().next();
  return format("Inconsistent %s data detected on file '%s'. " +
   "File source may have been modified while analysis was running.",
   dataWording,
   file.getName());
 }
 String lineHeader = "\n   ° ";
 return format("Inconsistent %s data detected on some files (%s in total). " +
  "File source may have been modified while analysis was running.", dataWording, filesWithErrors.size())
  + filesWithErrors.stream()
   .sorted(COMPONENT_COMPARATOR)
   .limit(5)
   .map(Component::getName)
   .collect(joining(lineHeader, lineHeader, ""));
}

代码示例来源:origin: yu199195/myth

private List<LogVO> findByPage(final Set<byte[]> keys, final int start, final int pageSize) {
  return keys.parallelStream()
      .skip(start).limit(pageSize)
      .map(this::buildVOByKey)
      .filter(Objects::nonNull)
      .collect(Collectors.toList());
}

代码示例来源:origin: google/error-prone

/**
  * Build the diagnostic message.
  *
  * <p>Examples:
  *
  * <ul>
  *   <li>Non-exhaustive switch, expected cases for: FOO
  *   <li>Non-exhaustive switch, expected cases for: FOO, BAR, BAZ, and 42 others.
  * </ul>
  */
 private String buildMessage(Set<String> unhandled) {
  StringBuilder message =
    new StringBuilder(
      "Non-exhaustive switch; either add a default or handle the remaining cases: ");
  int numberToShow =
    unhandled.size() > MAX_CASES_TO_PRINT
      ? 3 // if there are too many to print, only show three examples.
      : unhandled.size();
  message.append(unhandled.stream().limit(numberToShow).collect(Collectors.joining(", ")));
  if (numberToShow < unhandled.size()) {
   message.append(String.format(", and %d others", unhandled.size() - numberToShow));
  }
  return message.toString();
 }
}

代码示例来源:origin: apache/storm

/**
 * Get the last N elements as a new list.
 *
 * @param list list to get
 * @param count element count to get
 * @return the first element. null if list is null.
 *         elements in a new list may be less than count if there're not enough elements in the list.
 */
public static <T> List<T> takeLast(List<T> list, int count) {
  if (list == null) {
    return null;
  }
  if (list.size() <= count) {
    return list;
  } else {
    return list.stream()
        .skip(list.size() - count)
        .limit(count)
        .collect(Collectors.toList());
  }
}

代码示例来源:origin: SonarSource/sonarqube

private static List<Map.Entry<String, MetricStatsInt>> fiveBiggest(DistributedMetricStatsInt distributedMetricStatsInt, ToIntFunction<MetricStatsInt> biggerCriteria) {
 Comparator<Map.Entry<String, MetricStatsInt>> comparator = Comparator.comparingInt(a -> biggerCriteria.applyAsInt(a.getValue()));
 return distributedMetricStatsInt.getForLabels()
  .entrySet()
  .stream()
  .sorted(comparator.reversed())
  .limit(5)
  .collect(MoreCollectors.toList(5));
}

相关文章