How to Convert a Java 8 Stream to an Array

How to convert a Java 8 Stream to an Array?

The easiest method is to use the toArray(IntFunction<A[]> generator) method with an array constructor reference. This is suggested in the API documentation for the method.

String[] stringArray = stringStream.toArray(String[]::new);

What it does is find a method that takes in an integer (the size) as argument, and returns a String[], which is exactly what (one of the overloads of) new String[] does.

You could also write your own IntFunction:

Stream<String> stringStream = ...;
String[] stringArray = stringStream.toArray(size -> new String[size]);

The purpose of the IntFunction<A[]> generator is to convert an integer, the size of the array, to a new array.

Example code:

Stream<String> stringStream = Stream.of("a", "b", "c");
String[] stringArray = stringStream.toArray(size -> new String[size]);
Arrays.stream(stringArray).forEach(System.out::println);

Prints:

a
b
c

How to collect result of a stream into an array of custom object in Java 8

Use the terminal operation Stream::toArray which packs the sequence of items into an array. However, you have to define a provided generator IntFunction<A[]> to allocate the type of returned array:

Test[] array = testBuilders.stream().map(Test::build).toArray(size -> new Test[size]);

The lambda expression size -> new Test[size] should be replaced with a method reference:

Test[] array = testBuilders.stream().map(Test::build).toArray(Test[]::new);

Java stream toArray() convert to a specific type of array

Use toArray(size -> new String[size]) or toArray(String[]::new).

String[] strings = Arrays.stream(line.split(",")).map(String::trim).toArray(String[]::new);

This is actually a lambda expression for

.toArray(new IntFunction<String[]>() {
@Override
public String[] apply(int size) {
return new String[size];
}
});

Where you are telling convert the array to a String array of same size.

From the docs

The generator function takes an integer, which is the size of the desired array, and produces an array of the desired size. This can be concisely expressed with an array constructor reference:

 Person[] men = people.stream()
.filter(p -> p.getGender() == MALE)
.toArray(Person[]::new);

Type Parameters:

A - the element type of the resulting array

Parameters:

generator - a function which produces a new array of the desired type and the provided length

Java 8 Stream conversion of Array of Array of Class

Yes it is - you need a flatMap to achieve this

Stream.of(first.getSubjects())
.map(Subject::getPublisher)
.map(Publisher::getBooks)
.flatMap(Arrays::stream)
.map(Book::getBookId)
.collect(Collectors.toList());

If you want to have it null safe you need to add additional filtering like

List<String> collect = Stream.of(first.getSubjects())
.map(Subject::getPublisher)
.filter(Objects::nonNull) // filter all null publishers
.map(Publisher::getBooks)
.filter(Objects::nonNull) // filter all null book lists
.flatMap(Arrays::stream)
.map(Book::getBookId)
.filter(Objects::nonNull) // filter all null book ids
.collect(Collectors.toList());

How to convert a Java 8 Stream into a two dimensional array?

If you look at <A> A[] toArray(IntFunction<A[]> generator), you see that it converts a Stream<A> to a A[], which is a 1D array of A elements. So in order for it to create a 2D array, the elements of the Stream must be arrays.

Therefore you can create a 2D array if you first map the elements of your Stream to a 1D array and then call toArray:

Float[][] floatArray = 
map.entrySet()
.stream()
.map(key -> new Float[]{key.getKey().getPrice()})
.toArray(size -> new Float[size][1]);

Java 8 : Count the occurrence of digit 4 in the given int array

First, you need to obtain a stream from the given array of int[]. You can do it either by using the static method IntStream.of, or with Arrays utility class and it's method stream().

Both will give you an IntStream - a stream of int primitives. In order to collect stream elements into a list you need to convert it to a stream of objects. For that you can apply method boxed() on the stream pipeline and each int element will get wrapped with Integer object.

In order to find all elements in the given list that contain a target digit (4), you can turn the target digit into a string and then apply a filter based on it.

public static List<Integer> findOccurrencesOfDigit(List<Integer> source, 
int digit) {
String target = String.valueOf(digit);

return source.stream()
.filter(n -> String.valueOf(n).contains(target))
.collect(Collectors.toList());
}

main()

public static void main(String[] args) {
int[] nums = {48,44,4,88,84,16,12,13};

System.out.println(findOccurrencesOfDigit(nums, 4));
}

Output

[48, 44, 4, 84]

Note: method filter() expects a Predicate (a function represented by a boolean condition, that takes an element and return true of false)

Your attempt to create a predicate filter(n -> n % 10) is incorrect syntactically and logically. n % 10 doesn't produce a boolean value, it'll give the right most digit of n.

If you want to use modulus (%) operator to create a predicate, you have to divide the element by 10 in a loop until it'll not become equal to 0. And check before every division weather remainder is equal to the target digit. It could be done like that:

public static boolean containsDigit(int candidate, int digit) {
boolean flag = false;
while (candidate != 0) {
if (candidate % 10 == digit) {
flag = true;
break;
}
candidate /= 10; // same as candidate = candidate / 10;
}
return flag;
}

You can utilize this method inside a lambda expression like that (note: it's a preferred way to avoid multiline lambda expressions by extracting them into separate methods)

filter(n -> containsDigit(n, digit))

convert listObject to array of Id in java 8 stream

You can use <A> A[] toArray(IntFunction<A[]> generator) from Stream:

Integer[] ids = coll.stream()
.map(am -> am.getId())
.toArray(Integer[]::new)

which will create array from the stream rather than a list.

Convert an array into map using stream

Your current stream pipeline converts the original values to new values, so you can't collect it into a Map that contains both the original values and the new values.

You can achieve it if instead of map you use .collect(Collectors.toMap()) and perform the multiplication in toMap():

Map<Integer,Integer> map =
myList.stream()
.collect(Collectors.toMap(Function.identity(),
n -> n * 5));

In you still want to use map, you can retain the original values by converting each of them to a Map.Entry:

Map<Integer,Integer> map =
myList.stream()
.map (n -> new SimpleEntry<> (n, n * 5))
.collect(Collectors.toMap(Map.Entry::getKey,
Map.Entry::getValue));

Convert List of one type to Array of another type using Java 8

I would write it like this:

securityPolicyIds.stream()
.map(Long::valueOf)
.map(TeamsNumberIdentifier::new)
.toArray(TeamsNumberIdentifier[]::new);


Related Topics



Leave a reply



Submit