Java stream api limit

Java Stream limit()

Stream limit(n) is used to retrieve a number of elements from the Stream while the count must not be greater than n. The limit() method returns a new Stream consisting of the elements of the given stream, truncated to be no longer than maxSize in length.

Here maxSize the number of elements the stream should be limited to; and the method return value is a new Stream consisting of elements picked from the original stream.

  • Stream.limit() method is short-circuiting intermediate operation. An intermediate operation is short-circuiting if, when presented with infinite input, it may produce a finite stream as a result. Please note that a terminal operation is short-circuiting if, when presented with infinite input, it may terminate in finite time.
  • It returns a stream consisting of the maximum elements, no longer than given size in length, of current stream.
  • Generally, limit() is cheap operation but may sometimes be expensive if maxSize has a large value and stream is parallely processed.
  • Using an unordered stream source (such as generate(Supplier) ) or removing the ordering constraint with BaseStream.unordered() may result in significant speedups of limit() in parallel pipelines.
  • limit() returns the first n elements in the encounter order.

Example 1: Getting first 10 even numbers from an infinite stream of even numbers

In the given below example, we are creating an infinite stream using iterate() method. Then we are taking the first 10 even numbers using the method limit(10) .

Finally, we are collecting the even numbers from the stream into a List using collect(Collectors.toList()) method.

Stream evenNumInfiniteStream = Stream.iterate(0, n -> n + 2); List newList = evenNumInfiniteStream.limit(10) .collect(Collectors.toList()); System.out.println(newList); 

3. Difference between skip() and limit()

  • The limit(N) method returns first N elements in the encounter order of the Stream.
  • The skip(N) discards the first N elements of the Stream.
List list = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) .skip(6) .collect(Collectors.toList()); System.out.println(newList); //[7, 8, 9, 10]

Java 8 Stream limit() method can be useful in certain cases where we need to get the elements from a stream and the count of elements will be determined at runtime.

The fact, that it returns the elements in encounter order, makes it very useful for normal business usecases as well.

Читайте также:  What is recursive function in php

Источник

Java stream api limit

Метод skip(long n) используется для пропуска n элементов. Этот метод возвращает новый поток, в котором пропущены первые n элементов.

Метод limit(long n) применяется для выборки первых n элементов потоков. Этот метод также возвращает модифицированный поток, в котором не более n элементов.

Зачастую эта пара методов используется вместе для создания эффекта постраничной навигации. Рассмотрим, как их применять:

Stream phoneStream = Stream.of("iPhone 6 S", "Lumia 950", "Samsung Galaxy S 6", "LG G 4", "Nexus 7"); phoneStream.skip(1) .limit(2) .forEach(s->System.out.println(s));

В данном случае метод skip пропускает один первый элемент, а метод limit выбирает два следующих элемента. В итоге мы получим следующий консольный вывод:

Lumia 950 Samsung Galaxy S 6

Вполне может быть, что метод skip может принимать в качестве параметра число большее, чем количество элементов в потоке. В этом случае будут пропущены все элементы, а в результирующем потоке будет 0 элементов.

И если в метод limit передается число, большее, чем количество элементов, то просто выбираются все элементы потока.

Теперь рассмотрим, как создать постраничную навигацию:

import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.*; import java.util.Scanner; public class Program < public static void main(String[] args) < Listphones = new ArrayList(); phones.addAll(Arrays.asList(new String[] )); int pageSize = 3; // количество элементов на страницу Scanner scanner = new Scanner(System.in); while(true)< System.out.println("Введите номер страницы: "); int page = scanner.nextInt(); if(page<1) break; // если число меньше 1, выходим из цикла phones.stream().skip((page-1) * pageSize) .limit(pageSize) .forEach(s->System.out.println(s)); > > >

В данном случае у нас набор из 10 элементов. С помощью переменной pageSize определяем количество элементов на странице — 3. То есть у нас получится 4 страницы (на последней будет только один элемент).

В бесконечном цикле получаем номер страницы и выбираем только те элементы, которые находятся на указанной странице.

Теперь введем какие-нибудь номера страниц, например, 4 и 2:

Введите номер страницы: 4 Lenovo S 850 Введите номер страницы: 2 Samsung Galaxy S 6 LG G 4 Xiaomi MI 5

Источник

Interface Stream

A sequence of elements supporting sequential and parallel aggregate operations. The following example illustrates an aggregate operation using Stream and IntStream :

 int sum = widgets.stream() .filter(w -> w.getColor() == RED) .mapToInt(w -> w.getWeight()) .sum(); 

In this example, widgets is a Collection . We create a stream of Widget objects via Collection.stream() , filter it to produce a stream containing only the red widgets, and then transform it into a stream of int values representing the weight of each red widget. Then this stream is summed to produce a total weight.

In addition to Stream , which is a stream of object references, there are primitive specializations for IntStream , LongStream , and DoubleStream , all of which are referred to as «streams» and conform to the characteristics and restrictions described here.

To perform a computation, stream operations are composed into a stream pipeline. A stream pipeline consists of a source (which might be an array, a collection, a generator function, an I/O channel, etc), zero or more intermediate operations (which transform a stream into another stream, such as filter(Predicate) ), and a terminal operation (which produces a result or side-effect, such as count() or forEach(Consumer) ). Streams are lazy; computation on the source data is only performed when the terminal operation is initiated, and source elements are consumed only as needed.

A stream implementation is permitted significant latitude in optimizing the computation of the result. For example, a stream implementation is free to elide operations (or entire stages) from a stream pipeline — and therefore elide invocation of behavioral parameters — if it can prove that it would not affect the result of the computation. This means that side-effects of behavioral parameters may not always be executed and should not be relied upon, unless otherwise specified (such as by the terminal operations forEach and forEachOrdered ). (For a specific example of such an optimization, see the API note documented on the count() operation. For more detail, see the side-effects section of the stream package documentation.)

Collections and streams, while bearing some superficial similarities, have different goals. Collections are primarily concerned with the efficient management of, and access to, their elements. By contrast, streams do not provide a means to directly access or manipulate their elements, and are instead concerned with declaratively describing their source and the computational operations which will be performed in aggregate on that source. However, if the provided stream operations do not offer the desired functionality, the BaseStream.iterator() and BaseStream.spliterator() operations can be used to perform a controlled traversal.

A stream pipeline, like the «widgets» example above, can be viewed as a query on the stream source. Unless the source was explicitly designed for concurrent modification (such as a ConcurrentHashMap ), unpredictable or erroneous behavior may result from modifying the stream source while it is being queried.

  • must be non-interfering (they do not modify the stream source); and
  • in most cases must be stateless (their result should not depend on any state that might change during execution of the stream pipeline).

Such parameters are always instances of a functional interface such as Function , and are often lambda expressions or method references. Unless otherwise specified these parameters must be non-null.

A stream should be operated on (invoking an intermediate or terminal stream operation) only once. This rules out, for example, «forked» streams, where the same source feeds two or more pipelines, or multiple traversals of the same stream. A stream implementation may throw IllegalStateException if it detects that the stream is being reused. However, since some stream operations may return their receiver rather than a new stream object, it may not be possible to detect reuse in all cases.

Streams have a BaseStream.close() method and implement AutoCloseable . Operating on a stream after it has been closed will throw IllegalStateException . Most stream instances do not actually need to be closed after use, as they are backed by collections, arrays, or generating functions, which require no special resource management. Generally, only streams whose source is an IO channel, such as those returned by Files.lines(Path) , will require closing. If a stream does require closing, it must be opened as a resource within a try-with-resources statement or similar control structure to ensure that it is closed promptly after its operations have completed.

Stream pipelines may execute either sequentially or in parallel. This execution mode is a property of the stream. Streams are created with an initial choice of sequential or parallel execution. (For example, Collection.stream() creates a sequential stream, and Collection.parallelStream() creates a parallel one.) This choice of execution mode may be modified by the BaseStream.sequential() or BaseStream.parallel() methods, and may be queried with the BaseStream.isParallel() method.

Источник

Оцените статью