java - Sort List of Objects by values from array; -
i have list<brand> categories;
1000+ items.
for each item list have id
, use categories.getid();
and have array int[] sortedidarr = {4,53,102,403,110,5,6,8,12};
i sort categories
list , make order id
how in sortedidarr
. how can implement ?
private void sortbrandsbyid(list<brand> categories) { collections.sort(categories, new comparator<brand>() { public int compare(brand o1, brand o2) { } }); }
can use collections.sort
?
typically use collections.sort
, or equivalent idioms in java 8 if applicable, or sorted collection
such treeset
.
however in case want follow pre-defined order, dictated sortedidarr
array.
one way achieve use linked collection (e.g. linkedhashset
).
then iterate sortedidarr
array, , search list<brand>
object given id.
if found, add brand
object given id linkedhashset
, retain insertion order.
note if id not found, set
not "match" 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; } // 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 id array in order arrays.stream(sortedidarr) .foreach((i) -> { // retrieving brand same id current // "randomly" ordered list optional<brand> toadd = categories.stream() .filter((b) -> b.getid() == i) .findfirst(); // making sure there's 1 if (toadd.ispresent()) { // adding linked set linked.add(toadd.get()); } } ); system.out.println(linked); } }
output
[brand: 4, brand: 53, brand: 102]
imperative idiom older java versions
for (int i: sortedidarr) { (brand b: categories) { // assuming no nulls if (b.getid() == i) { linked.add(b); break; } } }
Comments
Post a Comment