com.tinkerpop.gremlin.tinkergraph.process.computer.TinkerMapEmitter Maven / Gradle / Ivy
The newest version!
package com.tinkerpop.gremlin.tinkergraph.process.computer;
import com.tinkerpop.gremlin.process.computer.KeyValue;
import com.tinkerpop.gremlin.process.computer.MapReduce;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
/**
* @author Marko A. Rodriguez (http://markorodriguez.com)
*/
public class TinkerMapEmitter implements MapReduce.MapEmitter {
public Map> reduceMap;
public Queue> mapQueue;
private final boolean doReduce;
public TinkerMapEmitter(final boolean doReduce) {
this.doReduce = doReduce;
if (this.doReduce)
this.reduceMap = new ConcurrentHashMap<>();
else
this.mapQueue = new ConcurrentLinkedQueue<>();
}
@Override
public void emit(K key, V value) {
if (this.doReduce)
this.reduceMap.computeIfAbsent(key, k -> new ConcurrentLinkedQueue<>()).add(value);
else
this.mapQueue.add(new KeyValue<>(key, value));
}
protected void complete(final MapReduce mapReduce) {
if (!this.doReduce && mapReduce.getMapKeySort().isPresent()) {
final Comparator comparator = mapReduce.getMapKeySort().get();
final List> list = new ArrayList<>(this.mapQueue);
Collections.sort(list, Comparator.comparing(KeyValue::getKey, comparator));
this.mapQueue.clear();
this.mapQueue.addAll(list);
} else if (mapReduce.getMapKeySort().isPresent()) {
final Comparator comparator = mapReduce.getMapKeySort().get();
final List>> list = new ArrayList<>();
list.addAll(this.reduceMap.entrySet());
Collections.sort(list, Comparator.comparing(Map.Entry::getKey, comparator));
this.reduceMap = new LinkedHashMap<>();
list.forEach(entry -> this.reduceMap.put(entry.getKey(), entry.getValue()));
}
}
}