Using a collector in a primitive stream

Is there any way in Java 8 to use Stream :: collect (Collector) in primitive streams?

Usually a Stream<Integer>as an example has two methods for collecting:

However, there IntStreamis only one way to collect it:

Now, as an example of code, I have the following:

@Override
public void run() {
    result = LongStream.range(1, maximum).boxed()
            .collect(Collectors.toMap(i -> i, i -> (int)Iterators.longStream(new CollatzGenerator(i)).count()))
            .entrySet().stream()
            .max(Comparator.comparingLong(Map.Entry::getValue))
            .get().getKey();
}

As you can see, I first put the primitives in order to be able to use the method Collectors..

Is there a way to use primitives and still have the same code with Collectors.toMap

+4
source share
2 answers

Map - , Map . , Map , , , ( , Map.Entry). Map.Entry :

LongStream.range(1, maximum)
  .mapToObj(i->new AbstractMap.SimpleEntry<>(i, Iterators.longStream(new CollatzGenerator(i)).count()))
  .max(Comparator.comparingLong(Map.Entry::getValue))
  .get().getKey();

, , Map.Entry, :

static final class TwoLongs {
    final long key, value;
    TwoLongs(long k, long v) { key=k; value=v; }
    public long getKey() { return key; }
    public long getValue() { return value; }
}

long s:

LongStream.range(1, maximum)
  .mapToObj(i->new TwoLongs(i, Iterators.longStream(new CollatzGenerator(i)).count()))
  .max(Comparator.comparingLong(TwoLongs::getValue))
  .get().getKey();

, - , ( TwoLongs) ( Map.Entry long s).

+4
long result = LongStream.range(0, 9)
        .mapToObj(i -> new long[]{i, i})
        .max(Comparator.comparingLong(pair -> pair[1]))
        .get()[0];
0

Source: https://habr.com/ru/post/1528808/


All Articles