Update: the result of the blog below landed here. Thanks to Nathan Freeman, hihi, kudos to me???
In Lotus Script it was not a simple task to sort a document collection. In Java it sort of is.
Idea: use a comparator class, supply with an array of fields upon which the “sorting” should happen and let the Collections.sort do it’s magic:
Comparator class:
public class CollectionComparator implements Comparator<Document> {
String[] sortFields = null;
public CollectionComparator(String[] sortFields) {
this.sortFields = sortFields;
}
public int compare(Document doc1, Document doc2) {
try {
int compared = 0;
// loop all sortFields
for (String field : sortFields) {
Item item1 = doc1.getFirstItem(field);
Item item2 = doc2.getFirstItem(field);
switch (item1.getType()) {
case Item.TEXT:
case Item.AUTHORS:
case Item.NAMES:
case Item.READERS:
String val1 = doc1.getItemValueString(field);
String val2 = doc2.getItemValueString(field);
compared = val1.compareTo(val2);
if (0 != compared) {
return compared;
}
break;
case Item.NUMBERS:
Double d1 = doc1.getItemValueDouble(field);
Double d2 = doc2.getItemValueDouble(field);
compared = d1.compareTo(d2);
if (0 != compared) {
return compared;
}
break;
case Item.DATETIMES:
DateTime dt1 = item1.getDateTimeValue();
DateTime dt2 = item2.getDateTimeValue();
compared = dt2.timeDifference(dt1);
if (0 != compared) {
return compared;
}
break;
}
item1.recycle();
}
return 0;
} catch (NotesException e) {
Logger.logError(e);
}
return 0;
}
}
Can you add an Apache License 2.0 to this post? If you do, I'll do something fun for you. 🙂
Hi Nathan.. hmmm don't know how to "add a license"..
just use the code and mention me as "author with no rights"
I'd like to add: maybe you wanna share what you are about to do with it? 🙂
Check out the about page on my blog. http://nathantfreeman.wordpress.com/about/
It has the license stuff there. If you add something similar to your own, then I can reuse your code in OpenNTF projects. 🙂
I will from now on add a line to the end of every post when it contains source code…
have done so in this post… I hope this is okay
Perfect. Check it out. 🙂
https://github.com/OpenNTF/org.openntf.domino/blob/nathan/org.openntf.domino/src/org/openntf/domino/helpers/DocumentComparator.java