how to order by a customized comparator

63 views
Skip to first unread message

Zhang Jason

unread,
Jan 4, 2024, 4:07:10 AMJan 4
to Gremlin-users
our vertex has a timestamp property with this format Tue Oct 03 16:39:34 GMT 2023
I want to sort the vertex based on UTC long value
I write the following comparator and pass it into order().by(), but it does not work
can a Java Comparator be directly used inside by()?
```
Comparator<Vertex> timestampComparator2 = new Comparator<Vertex>() {

SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");

@Override
public int compare(Vertex o1, Vertex o2) {
String timestampString1 = o1.values(P.TIMESTAMP).next().toString();
String timestampString2 = o2.values(P.TIMESTAMP).next().toString();
Date timestamp1 = null;
Date timestamp2 = null;
try {
timestamp1 = dateFormat.parse(timestampString1);
timestamp2 = dateFormat.parse(timestampString2);
return timestamp1.compareTo(timestamp2);
} catch (ParseException e) {
e.printStackTrace();
}
return 0;
}
};
``` 

Ken Hu

unread,
Jan 19, 2024, 7:30:48 PMJan 19
to Gremlin-users
Yes, a Java Comparator should be able to be used directly inside of a by() modulator. I've tested something similar to your code and it works.

GraphTraversalSource g = TinkerGraph.open().traversal();
g.addV().property("date", "2021-02-01").iterate();
g.addV().property("date", "2023-07-22").iterate();
g.addV().property("date", "2022-05-12").iterate();

Comparator<Object> vertexComparator = new Comparator<Object>() {
    SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
    @Override
    public int compare(Object o1, Object o2) {
        try {
            Date leftDate = fmt.parse(o1.toString());
            Date rightDate = fmt.parse(o2.toString());
            return leftDate.compareTo(rightDate);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return 0;
    }
};

System.out.println(g.V().values("date").order().by(vertexComparator).toList());

[2021-02-01, 2022-05-12, 2023-07-22]

A couple quick notes:
1. I was getting parsing exceptions using the format provided in your examples so I had to change it.
2. I chose to call V().values() instead of calling values() on the returned Vertex as it is recommended to use the process API (although for this example they are mostly equivalent so either would work).

Reply all
Reply to author
Forward
0 new messages