Java stream integer to int

Java 8 – Как преобразовать IntStream в int или int[]

Несколько примеров Java 8 для получения примитива int из IntStream .

1. Внутренний поток -> int

package com.mkyong; import java.util.Arrays; import java.util.OptionalInt; import java.util.stream.IntStream; public class Java8Example1 < public static void main(String[] args) < int[] num = ; //1. int[] -> IntStream IntStream stream = Arrays.stream(num); // 2. OptionalInt OptionalInt first = stream.findFirst(); // 3. getAsInt() int result = first.getAsInt(); System.out.println(result); // 1 // one line System.out.println(Arrays.stream(num).findFirst().getAsInt()); // 1 > >
package com.mkyong; import java.util.Arrays; import java.util.OptionalInt; import java.util.stream.IntStream; public class Java8Example2 < public static void main(String[] args) < int[] num = ; //1. int[] -> IntStream IntStream stream = Arrays.stream(num); // 2. OptionalInt OptionalInt any = stream.filter(x -> x % 2 == 0).findAny(); // 3. getAsInt() int result = any.getAsInt(); System.out.println(result); // 2 or 4 > >

2. Instream ->int[] или целое число[]

package com.mkyong; import java.util.Arrays; import java.util.stream.IntStream; public class Java8Example3 < public static void main(String[] args) < int[] num = ; IntStream stream = Arrays.stream(num); // IntStream -> int[] int[] ints = stream.toArray(); IntStream stream2 = Arrays.stream(num); // IntStream -> Integer[] Integer[] integers = stream2.boxed().toArray(Integer[]::new); > >

Рекомендации

Источник

How can I convert a Stream into an Int?

I need to write numbers in a text file, then I have to read the file, and finally sume the numbers. I can write and read the file, but I don´t know how to make the math opperation.

package clase.pkg13.de.septiembre; import java.io.*; public class FicheroTexto < public static void main (String args[]) < try < PrintWriter salida = new PrintWriter ( new BufferedWriter(new FileWriter("C:\\Users\\Santiago\\Desktop\\prueba.txt"))); salida.println("1"); salida.println("2"); salida.close(); BufferedReader entrada = new BufferedReader(new FileReader("C:\\Users\\Santiago\\Desktop\\prueba.txt")); String s, s2 = new String(); while((s= entrada.readLine()) !=null) s2 = s2 + s + "\n"; System.out.println("Numbers:"+"\n"+s2); entrada.close(); >catch (java.io.IOException e) < // Do nothing >> > 

3 Answers 3

Use Integer.parseInt(string) to convert your strings into integers. Then you can do normal math operations on them.

parseInt public static int parseInt(String s) throws NumberFormatException Parses the string argument as a signed decimal integer. The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value or an ASCII plus sign '+' ('\u002B') to indicate a positive value. The resulting integer value is returned, exactly as if the argument and the radix 10 were given as arguments to the parseInt(java.lang.String, int) method. Parameters: s - a String containing the int representation to be parsed Returns: the integer value represented by the argument in decimal. Throws: NumberFormatException - if the string does not contain a parsable integer. 

Источник

Читайте также:  Java узнать текущую дату

Guide to IntStream in Java

Java IntStream class is a specialization of Stream interface for int primitive. It represents a stream of primitive int-valued elements supporting sequential and parallel aggregate operations.

IntStream is part of the java.util.stream package and implements AutoCloseable and BaseStream interfaces.

There are several ways of creating an IntStream .

This function returns a sequential ordered stream whose elements are the specified values.

It comes in two versions i.e. single element stream and multiple values stream.

  • IntStream of(int t) – Returns stream containing a single specified element.
  • IntStream of(int. values) – Returns stream containing specified all elements.
IntStream.of(10); //10 IntStream.of(1, 2, 3); //1,2,3

1.2. Generating ints in Range

The IntStream produced by range() methods is a sequential ordered stream of int values which is the equivalent sequence of increasing int values in a for-loop and value incremented by 1. This class supports two methods.

  • range(int start, int end) – Returns a sequential ordered int stream from startInclusive (inclusive) to endExclusive (exclusive) by an incremental step of 1.
  • rangeClosed(int start, int end) – Returns a sequential ordered int stream from startInclusive (inclusive) to endInclusive (inclusive) by an incremental step of 1.
IntStream.range(1, 5); //1,2,3,4 IntStream.rangeClosed(1, 5); //1,2,3,4,5

1.3. Infinite Streams with Iteration

The iterator() function is useful for creating infinite streams. Also, we can use this method to produce streams where values are increment by any other value than 1.

Given example produces first 10 even numbers starting from 0.

IntStream.iterate(0, i -> i + 2).limit(10); //0,2,4,6,8,10,12,14,16,18

1.4. Infinite Streams with IntSupplier

The generate() method looks a lot like iterator(), but differs by not calculating the int values by incrementing the previous value. Rather an IntSupplier is provided which is a functional interface is used to generate an infinite sequential unordered stream of int values.

Читайте также:  В чем разница typescript и javascript

Following example create a stream of 10 random numbers and then print them in the console.

IntStream stream = IntStream .generate(() -> < return (int)(Math.random() * 10000); >); stream.limit(10).forEach(System.out::println);

To loop through the elements, stream support the forEach() operation. To replace simple for-loop using IntStream , follow the same approach.

IntStream.rangeClosed(0, 4) .forEach( System.out::println );

We can apply filtering on int values produced by the stream and use them in another function or collect them for further processing.

For example, we can iterate over int values and filter/collect all prime numbers up to a certain limit.

IntStream stream = IntStream.range(1, 100); List primes = stream.filter(ThisClass::isPrime) .boxed() .collect(Collectors.toList()); public static boolean isPrime(int i) < IntPredicate isDivisible = index ->i % index == 0; return i > 1 && IntStream.range(2, i).noneMatch(isDivisible); >

4. Converting IntStream to Array

Use IntStream.toArray() method to convert from the stream to int array.

int[] intArray = IntStream.of(1, 2, 3, 4, 5).toArray();

5. Converting IntStream to List

Collections in Java can not store the primitive values directly. They can store only instances/objects.

Using boxed() method of IntStream , we can get a stream of wrapper objects which can be collected by Collectors methods.

List list = IntStream.of(1,2,3,4,5) .boxed() .collect(Collectors.toList());

Источник

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