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
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.
- Найти индекс элемента в данном массиве в Java
- 1. Наивное решение — линейный поиск
- 2. Использование потока Java 8
- 3. Преобразовать в список
- 4. Бинарный поиск отсортированных массивов
- 5. Использование библиотеки Guava
- Java Array Indexof
- Get Index of an Element in an Integer Type Array in Java
- Get Index of an Array Element Using Java 8 Stream API in Java
- Get Index of an Array Element Using ArrayUtils.indexOf() in Java
- Related Article — Java Array
Найти индекс элемента в данном массиве в Java
В этом посте будет обсуждаться, как найти индекс элемента в массиве примитивов или объектов в Java.
Решение должно либо возвращать индекс первого вхождения требуемого элемента, либо -1, если его нет в массиве.
1. Наивное решение — линейный поиск
Наивное решение состоит в том, чтобы выполнить линейный поиск в заданном массиве, чтобы определить, присутствует ли целевой элемент в массиве.
2. Использование потока Java 8
Мы можем использовать Java 8 Stream для поиска индекса элемента в массиве примитивов и объектов, как показано ниже:
3. Преобразовать в список
Идея состоит в том, чтобы преобразовать данный массив в список и использовать List.indexOf() метод, который возвращает индекс первого вхождения указанного элемента в этом списке.
4. Бинарный поиск отсортированных массивов
Для отсортированных массивов мы можем использовать Алгоритм бинарного поиска для поиска указанного массива для указанного значения.
5. Использование библиотеки Guava
Библиотека Guava предоставляет несколько служебных классов, относящихся к примитивам, например Ints для инт, Longs надолго, Doubles на двоих, Floats для поплавка, Booleans для логического значения и так далее.
Каждый класс полезности имеет indexOf() метод, который возвращает индекс первого появления цели в массиве. Мы также можем использовать lastIndexOf() чтобы вернуть индекс последнего появления цели в массиве.
Guava’s com.google.commons.collect.Iterables класс содержит статический служебный метод indexOf(Iterator, Predicate) который возвращает индекс первого элемента, удовлетворяющего предоставленному предикату, или -1, если итератор не имеет таких элементов.
Java Array Indexof
- Get Index of an Element in an Integer Type Array in Java
- Get Index of an Array Element Using Java 8 Stream API in Java
- Get Index of an Array Element Using ArrayUtils.indexOf() in Java
This article introduces how to get the index of an array in Java using different techniques.
Get Index of an Element in an Integer Type Array in Java
There is no indexOf() method for an array in Java, but an ArrayList comes with this method that returns the index of the specified element. To access the indexOf() function, we first create an array of Integer and then convert it to a list using Arrays.asList() .
Notice that we use a wrapper class Integer instead of a primitive int because asList() only accepts wrapper classes, but they do return the result as a primitive data type. We can check the following example, where we specify the element i.e. 8 to the indexOf() method to get its index. The result we get from getIndex is of the int type.
import java.util.Arrays; public class ArrayIndexOf public static void main(String[] args) Integer[] array1 = 2, 4, 6, 8, 10>; int getIndex = Arrays.asList(array1).indexOf(8); System.out.println("8 is located at "+getIndex+" index"); > >
Get Index of an Array Element Using Java 8 Stream API in Java
We can use the Stream API to filter out the array items and get the position of the specified element. IntStream is an interface that allows a primitive int to use the Stream functions like filter and range .
range() is a method of IntStream that returns the elements from the starting position till the end of the array. Now we use filter() that takes a predicate as an argument. We use i -> elementToFind == array1[i] as the predicate where i is the value received from range() and elementToFind == array1[i] is the condition to check if the elementToFind matches with the current element of the array1 .
findFirst() returns the first element and orElse() returns -1 if the condition fails.
import java.util.stream.IntStream; public class ArrayIndexOf public static void main(String[] args) int[] array1 = 1, 3, 5, 7, 9>; int elementToFind = 3; int indexOfElement = IntStream.range(0, array1.length). filter(i -> elementToFind == array1[i]). findFirst().orElse(-1); System.out.println("Index of " + elementToFind + " is " + indexOfElement); > >
Get Index of an Array Element Using ArrayUtils.indexOf() in Java
This example uses the ArrayUtls class that is included in the Apache Commons Library. We use the below dependency to import the library functions to our project.
org.apache.commons commons-lang3 3.11
We use the indexOf() function of the ArrayUtils class to find the index of the array. indexOf() accepts two arguments, the first argument is the array, and the second argument is the element of which we want to find the index.
import org.apache.commons.lang3.ArrayUtils; public class ArrayIndexOf public static void main(String[] args) int[] array1 = 1, 3, 5, 7, 9>; int elementToFind = 9; int indexOfElement = ArrayUtils.indexOf(array1, elementToFind); System.out.println("Index of " + elementToFind + " is " + indexOfElement); > >
Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.
Related Article — Java Array
Copyright © 2023. All right reserved