1

After I have flattened int [][] into IntStream. I need to "split it back" into small 2 dimensional arrays following this algorithm:

IntSream [1,2,3,4] -> int [][] finalArr {{1,2},{2,3},{3,4}}

Basically,combining two nearest elements into array. I feel that it's possible to get over using flatMap again, but I can't figure out. Any suggestions?

3
  • codeint differentSquares(int[][] matrix) { // if(matrix[0].length<2 || matrix[1].length<2)return 0; Stream<int[]> stream = Arrays.stream(matrix); IntStream intStream = stream.filter(i->i.length>=2).flatMapToInt(x->Arrays.stream(x)); // intStream.forEach(System.out::println); return ...; }code Commented Jan 19, 2018 at 9:28
  • Does the input IntStream consist of a sequence of consecutive integers (such as [1, 2, 3, 4]), or could it also be any list of numbers (such as [1, 4, 3, 2])? Commented Jan 19, 2018 at 17:06
  • Nope, they are going randomly. Commented Jan 22, 2018 at 8:52

1 Answer 1

1

You can get List(list) from IntStream and use following code to create 2D array of two pairs:

import java.util.Arrays;
import java.util.List;
import  java.util.stream.IntStream;

public class Stream1 {
    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(1, 2, 3,4);

        int [][] int2DArray = IntStream.range(1, list.size())
                .mapToObj(i -> new int[] {list.get(i-1), list.get(i)})
                .toArray(int[][]:: new);

        System.out.println(Arrays.deepToString(int2DArray));
    }
}

Prints output:

[[1, 2], [2, 3], [3, 4]]
Sign up to request clarification or add additional context in comments.

9 Comments

The problem is that I also want to get [2 , 3] in the middle of them)
Since the question was specifically about an IntStream, there is no need for the List<Integer>. Further, there is no reason to use change the requested int[][] to Integer[][]. So you can do it as simple as int[][] int2DArray = IntStream.range(1, 4).mapToObj(i -> new int[] { i, i+1 }) .toArray(int[][]::new);
Holger and @FedericoPeraltaSchaffner: thanks for the inputs edited to int[][]
@AnuragSharma No, unless you use an external library, such as StreamEx. If you already have the index-based data structure (i.e. an ArrayList), the approach given in this answer is absolutely correct IMO.
@FedericoPeraltaSchaffner that’s giving by the OP’s example. Otherwise, we could simply use an int[] array as input. If the input is an unknown IntStream, just calling toArray() first, followed by this solution might be the simplest choice.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.