Using java 8 streams to generate pairs of integers

java pair
java stream reduce
java stream pair to list
java-stream zip
java-stream zip with index
java list of pairs
list of pairs to map java
java zip two lists

I am trying to generate pairs of integers - I have a class Pair with a constructor taking 2 ints. The following code works but seems rather clunky - in particular the conversion from an intStream to an object stream using mapToObj(Integer::new).

private static List<Pair> success() {
    return IntStream.range(0, 10).
            mapToObj(Integer::new).flatMap(i -> IntStream.range(12, 15).
                mapToObj(j -> new Pair(i, j))).
            collect(Collectors.toList());
}

Firstly does anyone have a more elegant way to do this ?

Secondly when I refactored to extract some streams as variables, I get an error: IllegalStateException: stream has already been operated upon or closed. Here is the refactored method - does anyone know if this a problem with the code ?

static List<Pair> fail() {
    Stream<Integer> outer = IntStream.range(0, 10).mapToObj(Integer::new);
    IntStream inner = IntStream.range(12, 15);
    Stream<Pair> pairStream = outer.flatMap(i -> 
            inner.mapToObj(j -> new Pair(i, j)));
    return pairStream.collect(Collectors.toList());
}

It is possible to make it a bit more concise by replacing mapToObj(Integer::new) with boxed- but apart from that, Java is not that concise:

IntStream.range(0, 10)
        .boxed()
        .flatMap(i -> IntStream.range(12, 15)
                               .mapToObj(j -> new Pair(i, j)))
        .collect(Collectors.toList());

As for the second question: There are other answers which link to the problem. The concrete problem is that inner is not used once, but each time of the outer flatMap().

This way it works:

        final IntStream range = IntStream.range(0, 10);
        List<Pair> ps =  range
               .boxed().flatMap(i -> {
                   final IntStream range1 = IntStream.range(12, 15);
                   return range1.
                           mapToObj(j -> new Pair<>(i, j));
               }).
            collect(Collectors.toList());

Getting started with Java 8 Streams, The launch of Java8 brings with it the Streams-API. But what are <Pair>builder​().add(new Pair()).build(); Stream.generate(() -> { final Pair p = new Pair(); p.id = random. toSet()); //Stream to Map final Map<Integer,List<Pair>>  Generating Streams. With Java 8, Collection interface has two methods to generate a Stream. stream() − Returns a sequential stream considering collection as its source. parallelStream() − Returns a parallel Stream considering collection as its source.

Why not use plain for-loops? Plain for-loops will:

  1. Look nicer
  2. Make your intent clear

static List<Pair> fail() {
    List<Pair> pairs = new ArrayList<>(30);

    for (int i = 0; i < 10; i++) {
        for (int j = 12; j < 15; j++) {
            pairs.add(new Pair(i, j));
        }
    }

    return pairs;
}

Java 8 – flatmap to find a pair of elements from two List, Today we will see how using java 8 stream flatmap method we can wind 4); List<Integer[]> pairs = list1.stream() .map(i -> list2.stream() .map(j  The Java 8 streams library is primarily geared toward splitting streams into smaller chunks for parallel processing, so stateful pipeline stages are quite limited, and doing things like getting the index of the current stream element and accessing adjacent stream elements are not supported.

If your Pair class accepts primitive ints you can eliminate the unnecessary boxing this way:

private static List<Pair> success() {
    return IntStream.range(0, 10).
            mapToObj(i -> IntStream.range(12, 15).
                mapToObj(j -> new Pair(i, j))).
            flatMap(Function.identity()).
            collect(Collectors.toList());
}

As for extracting streams into variables, you may create a supplier instead:

private static List<Pair> success() {
    Supplier<IntStream> inner = () -> IntStream.range(12, 15);
    return IntStream.range(0, 10).
            mapToObj(i -> inner.get().
                mapToObj(j -> new Pair(i, j))).
            flatMap(Function.identity()).
            collect(Collectors.toList());
}

Though it seems unnecessary for me to extract the stream into the variable.

Java 8 Create list of pairs from List of items. Java does not have Pair , Java 8 Create list of pairs from List of items. Java does not have public <T> List​<Pair<T, T>> toPairs(final Stream<T> s) { final int i = counter. IntStream is a stream of primitive int values. It's part of the java.util.stream package, and you can find a lot of the same functions there as in the normal Stream<T>. There also exists streams for dealing with double and long primitives, but we'll leave that out since it acts in pretty much the same way.

Part 2: Processing Data with Java SE 8 Streams, Combine advanced operations of the Stream API to express rich data processing queries. Originally published in the May/June 2014 issue of Java Magazine. int sumExpensive = transactions.stream() .filter(t -> t. The code in Listing 9 shows how to generate the set of only the cities that have expensive transactions. Convert a List to a Comma-Separated String in Java 8 This quick tutorial shows you how to use streams in Java to convert the contents of a list to a comma-separated string in Java 8. by

On Java 8, public Pair-Integer, String- get() { return new Pair->(number----, "" + letter++); } Map<Integer, String- m = Stream. generate(new Letters()) .limit (11) . collect  The following one-liner Java 8 version will generate [ 1, 2 ,3 10 ]. The first arg of iterate is the first nr in the sequence, and the first arg of limit is the last number. List<Integer> numbers = Stream.iterate(1, n -> n + 1) .limit(10) .collect(Collectors.toList());

Chapter 5. Working with streams, Streams API. You will learn about operations available in Java 8 and also new additions in Java 9. asList(3, 4); List<int[]> pairs = numbers1.stream() . For example, suppose you'd like to generate all numbers between 1 and 100. Java 8​  Java 8 Create list of pairs from List of items. Java does not have Pair and groupBy uses AtomicInteger trick. Raw.

Comments
  • answer to your second question - stackoverflow.com/questions/27990451/…
  • If you know a little maths you can do IntStream.range(0, 30).mapToObj(i -> new Pair(i/3, 12 + i%3)).collect(Collectors.toList());, but I agree with @Jeffrey. Nothing is going to be clearer than nested for loops.
  • static imports for IntStream.range and Collectors.toList will help reduce the information-sparse bulk.
  • static imports for IntStream.range and Collectors.toList will help reduce the bulk.
  • What OP needs is actually not zipping, it's cartesian product.