Typically you would use Collections.sort, or the equivalent idioms in Java 8 if applicable, or a sorted Collection such as TreeSet.
However in this case you want to follow a pre-defined order, dictated by your sortedIdArr array.
One way to achieve that is to use a linked collection (e.g. a LinkedHashSet).
Then you iterate your sortedIdArr array, and search your List<Brand> for an object with the given ID.
If found, you add the Brand object with the given ID to your LinkedHashSet, which will retain the insertion order.
Note that if an ID is not found, your Set will not exactly "match" the array.
Self-enclosed example, using Java 8
package test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
public class Main {
// simplified Brand pojo
static class Brand {
int id;
public Brand(int id) {
this.id = id;
}
public int getId() {
return id;
}
// for output clarity
@Override
public String toString() {
return String.format("Brand: %d", id);
}
}
public static void main(String[] args) throws Exception {
// simplified ID list
int[] sortedIdArr = {4,53,102};
// "randomly" ordered Brand list
final List<Brand> categories = new ArrayList<Brand>() {
{
add(new Brand(1));
add(new Brand(102));
add(new Brand(53));
add(new Brand(4));
add(new Brand(0));
}
};
// destination: linked set
Set<Brand> linked = new LinkedHashSet<Brand>();
// streaming the ID array in order
Arrays.stream(sortedIdArr)
.forEach((i) -> {
// retrieving a Brand with same ID as the current
// from the "randomly" ordered list
Optional<Brand> toAdd = categories.stream()
.filter((b) -> b.getId() == i)
.findFirst();
// making sure there's one
if (toAdd.isPresent()) {
// adding to linked set
linked.add(toAdd.get());
}
}
);
System.out.println(linked);
}
}
Output
[Brand: 4, Brand: 53, Brand: 102]
Imperative idiom for older Java versions
for (int i: sortedIdArr) {
for (Brand b: categories) {
// assuming no nulls
if (b.getId() == i) {
linked.add(b);
break;
}
}
}
sortedIdArrand compare these indices. If the index ofo1-IDis smaller thano2-ID, then it should return1,-1of smaller and0if equal.