sgx
sgx

Reputation: 1317

Split Integers Using Stream Lambda

I was studying usage of Stream and Lambda in Java8. How would you go about applying Stream and Lambda for the following: Print out the odd integers in the following string: "[3, 6, 8, 96, 7, 23]" using Stream and Lambda.

I figured out it was pretty simple using a for loop and parseInt but how would one implement streams and lambda.

Upvotes: 1

Views: 998

Answers (2)

Peter Gyschuk
Peter Gyschuk

Reputation: 1029

Converting String to String[] by splitting it by "[", "]", " ", and "," then filtering blank values and not odd integers

Arrays.stream("[3, 6, 8, 96, 7, 23]".split("[,\\s\\[\\]]"))
.filter(s->!s.isBlank() && Integer.valueOf(s)%2!=0)
.forEach(s-> System.out.println(s));

Upvotes: 1

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59960

You can use substring with split like so :

String str = "[3, 6, 8, 96, 7, 23]";
Arrays.stream(str.substring(1, str.length() - 1).split(", "))
        .filter(s -> Integer.valueOf(s) % 2 != 0)
        .forEach(System.out::println);

Or if you want to get an array, then you can use toArray like so :

.toArray(String[]::new);

Or if you want to get an array of Integers, you can use a map then a filter like so :

Integer[] array = Arrays.stream(str.substring(1, str.length() - 1).split(", "))
        .map(Integer::valueOf)
        .filter(i -> i % 2 != 0)
        .toArray(Integer[]::new);

Outputs

3
7
23

Upvotes: 5

Related Questions