开发者

Sort arraylist containing by object

i have ArrayList contains object named as AccountProductCode it has three parameter which is like for e.g.

  AccountProductCode accprocode = new AccountProductCode(); 
  accprocode.setAPPART("002");
  accprocode.setAPCODE("PC1");
  finalList.add(accprocode);

so here suppose list contain data like

APPART APCODE
001     PC1
002     PC2
003     PC3
004     PC4
*AL     PC1

i need to sort data like if A开发者_开发技巧PART *AL has same APCODE which is like other APART then i need exclude that APCODE. so the list will be like

APCODE
PC1
PC2
PC3
PC4

how can i do the program using ArrayList don't use Set..

and list should be sorted...

kindly check my new exact statment....Builds and returns a List object will all AccountProductCode objects for the participantID and participant ID *AL. If a product code exists for participantID and *AL, exclude the product code for *AL. The list should be sorted by the product code value.

Thanks Vinod


I'd simply write a new arraylist with the filtered data:

List<AccountProductCode> filtered = new ArrayList<AccountProductCode>();
Set<String> apcodes = new HashSet<String>();
for (AccountProductCode code:getList()) {   // some magic to get the current list
  String apcode = code.getApCode();
  if (apcode.equals("*AL") && apcodes.contains(apcode)) {
     // skip duplicates
     continue;
  } else {
     apcodes.add(apcode);
     filtered.add(code);
  }
}

The filtered list is free of duplicates (according to your custom rule).


Rewrite: Now I'm no longer using an external set or map. The price for this is that I have to potentially iterate over the entire list for every add (horrible performance):

Add items like this:

public boolean addUniqueItem(List<AccountProductCode> list,
                             AccountProductCode item){
    for(AccountProductCode existingItem : list){
        if(item.getApart().equals(existingItem.getApart())return false;
    }
    return list.add(item);
}

Then sort the list like this:

Collections.sort(list, new Comparator<AccountProductCode>(){
    public int compare(AccountProductCode a, AccountProductCode b){
        return a.getApCode().compareTo(b.apCode());
    }
});


Another possible solution would be in your object AccountProductCode add a compareTo method, so when you try to sort, it will use the compareTo, you can add some logic there if needed.


You should use a Set. If you are unwilling to use a set:

  1. sort by APCODE.
  2. iterate over the list looking at each APCODE and filtering unwanted items.
  3. if desired, sort by APPART.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜