简体   繁体   中英

Get a Sorted List by user

I need to get a list sorted by decreasing values of expenses, but by Taxpayer. Imagining the Taxpayer with number 1 has 3 expenses and the Taxpayer with number 2 has 2 expenses, I need to get the expenses from the first Taxpayer and sort them, then sort the expenses of Taxpayer number 2. What I had so far was:

 public TreeSet<Expense> getListFactIndivValor(){
   TreeSet<Expense> t = new TreeSet<Expense>(new ComparatorValue(-1)); //-1 because I had to use this comparator to do ascending order on another method
   Company c = (Company) this.users.get(userId); //Entity that issues expenses. has the method getExpenses. Gets the Company logged in.
   for(User u: this.users.values()){ //this.users has all the users on the system
       if(!u.getUserType()){ // If user is Taxpayer
           for(Expense e: c.getExpenses().values()){ //gets all the expenses of the Company.
             if(u.getTIN().equals(e.getTINUser())){ //if the user TIN is the same that the one on expense
                  t.add(e.clone());
             }
           }
       }
   }
   return t; 

}

What I think is happening is he goes through each Taxpayer like I intend, but then it's just ordering it by value, not taking into consideration that I need to have it by each Taxpayer.

A Set ( TreeSet ) is not designed to have a specific order. Rather use an ArrayList as the result of your method.

You have to do two steps:

  1. Sort the expenses to the user it belong to (using a TreeMap which is sortable)
  2. Iterate on the (sorted) users and extract the her expenses.

     public List<Expense> getListFactIndivValor() { Comparator<TINUser> comparator = TINUser::compareTo; TreeMap<TINUser, List<Expense>> map = new TreeMap<>( comparator); Company c = new Company(); for ( Expense e : c.getExpenses() ) { List<Expense> expenses = map.get( e.getTINUser()); if ( expenses == null ) { expenses = new ArrayList<>(); map.put( e.getTINUser(), expenses); } expenses.add( e); } List<Expense> result = new ArrayList<>(); for ( TINUser u : map.descendingKeySet() ) { List<Expense> expenses = map.get( u); for ( Expense expense : expenses ) { result.add( expense); } } return result; } 

Implement a compareTo() method in your TINUser class which defines the sort criteria.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM