按用户获取排序列表

时间:2018-05-18 14:51:02

标签: java

我需要通过降低费用值来排序列表,但需要纳税人。想象纳税人1号有3个费用而2号纳税人有2个费用,我需要从第一个纳税人那里得到费用并对它们进行分类,然后对纳税人2号的费用进行分类。到目前为止,我所做的是:< / p>

 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; 

}

我认为正在发生的事情是他按照我的意愿通过每个纳税人,但是它只是按价值排序,而不是考虑到每个纳税人都需要它。

1 个答案:

答案 0 :(得分:1)

SetTreeSet)并非设计为具有特定订单。而是使用ArrayList作为方法的结果。

您必须执行两个步骤:

  1. 将费用分配给它所属的用户(使用可排序的TreeMap)
  2. 迭代(已排序)用户并提取她的费用。

    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;
    }
    
  3. 在TINUser类中实现compareTo()方法,该方法定义排序条件。