Skip to content

Commit c5fff84

Browse files
committed
ToMany: Set an comparator to define the order of entities
1 parent 92131f8 commit c5fff84

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

objectbox-java/src/main/java/io/objectbox/relation/ToMany.java

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,7 @@ public class ToMany<TARGET> implements List<TARGET>, Serializable {
7272
transient private Box entityBox;
7373
transient private volatile Box<TARGET> targetBox;
7474
transient private boolean removeFromTargetBox;
75+
transient private Comparator<TARGET> comparator;
7576

7677
public ToMany(Object sourceEntity, RelationInfo<TARGET> relationInfo) {
7778
if(sourceEntity == null ) {
@@ -93,6 +94,12 @@ public void setListFactory(ListFactory listFactory) {
9394
this.listFactory = listFactory;
9495
}
9596

97+
/** Set an comparator to define the order of entities. */
98+
@Experimental
99+
public void setComparator(Comparator<TARGET> comparator) {
100+
this.comparator = comparator;
101+
}
102+
96103
/**
97104
* On put, this also deletes removed entities from the target Box.
98105
* Note: removed target entities won't cascade the delete.
@@ -162,6 +169,9 @@ private void ensureEntities() {
162169
newEntities = targetBox.internalGetBacklinkEntities(relationInfo.targetInfo.getEntityId(),
163170
relationInfo.targetIdProperty, id);
164171
}
172+
if(comparator != null) {
173+
Collections.sort(newEntities, comparator);
174+
}
165175
synchronized (this) {
166176
if (entities == null) {
167177
entities = newEntities;

tests/objectbox-java-test/src/main/java/io/objectbox/relation/RelationTest.java

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818

1919
import org.junit.Test;
2020

21+
import java.util.Comparator;
2122
import java.util.List;
2223

2324
import io.objectbox.query.Query;
@@ -55,6 +56,28 @@ public void testRelationToMany() {
5556
assertEquals("Oranges", orders.get(1).getText());
5657
}
5758

59+
@Test
60+
public void testRelationToMany_comparator() {
61+
Customer customer = putCustomer();
62+
putOrder(customer, "Bananas");
63+
putOrder(customer, "Oranges");
64+
putOrder(customer, "Apples");
65+
66+
ToMany<Order> orders = (ToMany<Order>) customer.getOrders();
67+
orders.setComparator(new Comparator<Order>() {
68+
@Override
69+
public int compare(Order o1, Order o2) {
70+
return o1.text.compareTo(o2.text);
71+
}
72+
});
73+
orders.reset();
74+
75+
assertEquals(3, orders.size());
76+
assertEquals("Apples", orders.get(0).getText());
77+
assertEquals("Bananas", orders.get(1).getText());
78+
assertEquals("Oranges", orders.get(2).getText());
79+
}
80+
5881
@Test
5982
public void testRelationToMany_activeRelationshipChanges() {
6083
Customer customer = putCustomer();

0 commit comments

Comments
 (0)