Например, {1, 1, 1, 2, 3 , 3, 4} сгруппируется как целое число для списка отображения индексов:
Код: Выделить всё
1 -> 0, 1, 2
2 -> 3
3 -> 4, 5
4 -> 6
Код: Выделить всё
@Test
public void testGrouping() throws Exception {
// actually it is being read from a disk file
Stream nums = Stream.of(1, 1, 1, 2, 3, 3, 4);
// list to map by index
int[] ind = {0}; // capture array, effectively final
class Pair {
int left;
int right;
public Pair(int left, int right) {
this.left = left;
this.right = right;
}
}
Map map = nums.map(e -> new Pair(ind[0]++, e))
.collect(Collectors.groupingBy(e -> e.right))
.entrySet().parallelStream()
.collect(Collectors.toConcurrentMap(
Map.Entry::getKey,
e -> e.getValue().parallelStream().map(ee -> ee.left).collect(Collectors.toList())
));
}
Я чувствую, что мой способ сделать это, как и выше, довольно неоптимальный. Есть ли лучший или более элегантный способ сделать это?
Подробнее здесь: https://stackoverflow.com/questions/279 ... ger-values