cancel
Showing results for 
Search instead for 
Did you mean: 

Head's Up! Site migration is underway. Phase 2: migrate recent content

Implementing user-defined function for merging overlapping intervals

Martynas
Node

Hello, I want to write a user-defined function that would take a list of lists as an input, with each 'inner' list containing 2 integers - start date and end date, for example:

Input: [[1,3],[2,6],[8,10],[15,18]]

and would return the list of lists with the overlapping intervals merged:

Output: [[1,6],[8,10],[15,18]]

My code so far:

package example;

import java.util.*;

import org.neo4j.procedure.Description;
import org.neo4j.procedure.Name;
import org.neo4j.procedure.UserFunction;

public class Merge {

@UserFunction
@Description("example.merge([[start_date1, end_date1],[start_date2, end_date2],...]) - returns non-overlapping intervals")
static ArrayList < List < Integer >> merge(@Name("intervals") ArrayList < List < Integer >> intervals) {

Collections.sort(intervals, (a,b)->a.get(0)-b.get(0));
ArrayList < List < Integer >> merged = new ArrayList < > ();

for (int i = 0; i < intervals.size(); i++) {
if (merged.isEmpty() || merged.get(merged.size() - 1).get(1) < intervals.get(i).get(0)) {
ArrayList < Integer > v = new ArrayList < > ();
v.add(intervals.get(i).get(0));
v.add(intervals.get(i).get(1));

merged.add(v);
} else {

merged.get(merged.size() - 1).set(1, Math.max(merged.get(merged.size() - 1).get(1), intervals.get(i).get(1)));
}
}

return merged;
}

The problem I have is that Cypher does not support a nested list-type of value type, as stated here - https://neo4j.com/docs/java-reference/current/extending-neo4j/values-and-types/ . When I try to start the DB after putting the .jar file inside Plugins directory, I get the error saying that:

 

type `ArrayList` cannot be converted to a Neo4j type: Don't know how to map
`java.util.ArrayList<java.util.List<java.lang.Integer>>` to the Neo4j Type System.

 

How could I circumvent this error and make the function work?

0 REPLIES 0
Nodes 2022
Nodes
NODES 2022, Neo4j Online Education Summit

All the sessions of the conference are now available online