java - Can we make the order of one list based on other? -
i have 2 array lists list1 , list2 , want list2 order order of list1. there way this? in 1 list got top performing emploee database , list 2 got database second time using top performing employee ids using "in" clause.
list<long> list1 = new arraylist<long>(); list1.add(5645); list1.add(2312); list1.add(7845); list1.add(1212); and other list of object type:
list<employee> list2 = new arraylist<employee>(); list2.add(new employee(1212, "a")); list2.add(new employee(2312, "v")); list2.add(new employee(5645, "d")); list2.add(new employee(7845, "t")); where list1 shows employee id of top 4;
and got employee detail data base using id , got list2.
now want make order of list2 list1 show on html page.
just iterate list1 , each item find matching element in list2. no need sort.
list<employee> sortedlist = new arraylist<>(); (long id : list1) { employee match = collectionutils.find(list2, e -> e.id.equals(id)); // cannot sort, if list2 not contain id, or put rule case assert match != null; sortedlist.add(match); } this uses apache commons collections's collectionutils.
or, better performance, build map first:
map<long, employee> lookupmap = new hashmap<>(list2.size()); (employee e : list2) lookupmap.put(e.id, e); list<employee> sortedlist = new arraylist<>(list2.size()); (long id : list1) sortedlist.add(lookupmap.get(id));
Comments
Post a Comment