-2

Oh. I have Java 8 and want to collect a

Map<K, V> 

from

Stream<Tuple2<K, V>>

I do not want to use Pair, because of verbose syntax. Is there any way to do

.collect(toMap(Tuple2::_1, Tuple2::_2))

Thanx

Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
Igor Yudnikov
  • 434
  • 1
  • 6
  • 14
  • 2
    What's the problem with `.collect(toMap(Tuple2::_1, Tuple2::_2))`? And what `Tuple2` class is that? – ernest_k Nov 09 '18 at 10:14
  • Oh... thanx man. Tuple2 is imported from vavr scala-like library. I'll do with pair. – Igor Yudnikov Nov 09 '18 at 10:18
  • @ernest_k I think the problem is that you can't access field values using the syntax for method references. – flakes Nov 09 '18 at 10:27
  • @flakes Maybe. Without knowing which `Tuple2` class that was, it was hard to tell whether `_1` or `_2` weren't methods... – ernest_k Nov 09 '18 at 10:29
  • 1
    @ernest_k ah nevermind, it looks like it is both a field and a method name! – flakes Nov 09 '18 at 10:30
  • Java 8 does not have `Tuple2` or `Pair` classes. What library is `Tuple2` coming from? What 'verbose syntax' are you referring to for `Pair` (again what library is `Pair` coming from)? What is the problem with the example you showed? – jbx Nov 09 '18 at 11:15

1 Answers1

2

AFAIK, This is not avoidable in java (compared to the way its done in scala.)

However If you're going to use a lot of Tuple to Map Conversions in your code and want to avoid verbose syntax, You could create a custom TupleCollector and add a toMap Method.

This might be the closet you'll get to scala.

static class TupleCollector {
        public static <K, V, T extends Tuple2<K, V>> Collector<T, ?, Map<K, V>> toMap() {
            return Collectors.toMap(T::_1, T::_2);
        }
    }

Code to Invoke

import static TupleCollector.toMap
...
myStream.collect(toMap());

PS: Then again, I wouldn't be surprised if this doesn't pass code review phase.

Kishore Bandi
  • 5,537
  • 2
  • 31
  • 52