Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get an IntStream from a List<Integer>?

I can think of two ways:

public static IntStream foo(List<Integer> list) {     return list.stream().mapToInt(Integer::valueOf); }  public static IntStream bar(List<Integer> list) {     return list.stream().mapToInt(x -> x); } 

What is the idiomatic way? Maybe there is already a library function that does exactly what I want?

like image 299
fredoverflow Avatar asked Jul 08 '14 14:07

fredoverflow


People also ask

How do I get an IntStream from an int?

Since you created a Stream with a single element, you can use findFirst() to get that element: int randInt = new Random(). ints(1,60,121). findFirst().

How do I get IntStream?

IntStream find valueUse findFirst() or findAny() methods on the InstStream object to get the first or any value. By default, IntStream is created as sequential stream unless call the parallel() on the IntStream. For sequential streams, the findFirst() and findAny() methods return the same result.

How does IntStream range () work?

range() method generates a stream of numbers starting from start value but stops before reaching the end value, i.e start value is inclusive and end value is exclusive. Example: IntStream. range(1,5) generates a stream of ' 1,2,3,4 ' of type int .


2 Answers

I guess (or at least it is an alternative) this way is more performant:

public static IntStream baz(List<Integer> list) {     return list.stream().mapToInt(Integer::intValue); } 

since the function Integer::intValue is fully compatible with ToIntFunction since it takes an Integer and it returns an int. No autoboxing is performed.

I was also looking for an equivalent of Function::identity, i hoped to write an equivalent of your bar method :

public static IntStream qux(List<Integer> list) {     return list.stream().mapToInt(IntFunction::identity); } 

but they didn't provide this identity method. Don't know why.

like image 67
gontard Avatar answered Oct 07 '22 15:10

gontard


An alternate way to transform that would be using Stream.flatMapToInt and IntStream.of as:

public static IntStream foobar(List<Integer> list) {     return list.stream().flatMapToInt(IntStream::of); } 

Note: Went through few linked questions before posting here and I just couldn't find this suggested in them either.

like image 20
Naman Avatar answered Oct 07 '22 13:10

Naman