How do I compare and count the elements of multiple threads in Java?
I have a stream of threads that contains items (nodes).
Stream<MyStreams>
MyStreams are of type:
Stream<Node>
So, Stream of Streams is of type:
Stream<Stream<Node>>
Multiple MyStreams can contain the same Node. I want to know how often a particular Node is contained in threads. The stream of the output class might look like this:
public class Output
{
public int count; //number of appereances of a specific node in all streams
public int nodeId; // ID of the node
Output()
{
...
}
}
The final list of results could be:
nodeId | count
12 | 7
14 | 5
28 | 4
... | ...
Thank you so much!
EDIT:
This is what I got so far:
public class Correlation {
@Context
public GraphDatabaseService db;
@Context
public Log log;
@Procedure
@Description("xxx")
// Main
public Stream<NeighborNodeStream> analysisNeighbors( @Name("label") String labelString,
@Name("key") String key,
@Name("value") String value)
{
Label label = Label.label(labelString);
// Get Stream of Starting Nodes
Stream<Node> myNodes = db.findNodes(label, key, value).stream();
// For every Stating node get Stream of Neighbor nodes
Stream<NeighborNodeStream> myNeighborNodeStreams = myNodes.map(x -> new NeighborNodeStream(x));
// ***Nodes count ***
return myNeighborNodeStreams;
}
public class NeighborNodeStream
{
public Stream<Node> neighborNodes;
public NeighborNodeStream(Node node)
{
Stream<Relationship> relsStream = StreamSupport.stream(node.getRelationships().spliterator(), false);
this.neighborNodes = relsStream.map(x -> getRightNode(x, node.getId()));
}
}
private Node getRightNode(Relationship rel, long nodeId)
{
long endId = rel.getEndNode().getId();
if (endId == nodeId)
return rel.getStartNode();
else
return rel.getEndNode();
}
}
+3
source to share
2 answers
List<Output> output = Stream.of(Stream.of(new Node(1), new Node(2)), Stream.of(new Node(2)))
.flatMap(x -> x)
.collect(Collectors.collectingAndThen(
Collectors.groupingBy(
Node::getNodeId,
Collectors.summingInt(n -> 1)),
map -> map.entrySet()
.stream()
.map(e -> new Output(e.getKey(), e.getValue()))
.collect(Collectors.toList())));
System.out.println(output); // [id = 1 count = 1, id = 2 count = 2]
+3
source to share
If I understand the OP correctly, this should be a simple question:
Stream<NeighborNodeStream> nodess = ...;
// key is the Node id, value is the occurrences:
Map<Long, Long> res = nodess.flatMap(s -> s.neighborNodes)
.collect(Collectors.groupingBy(n -> n.getId(), Collectors.counting()));
+2
source to share