如何对List <object>

时间:2019-01-24 14:51:19

标签: android

我想对“对象列表”的所有相似数字值求和。例如,如果我将各种Expense expense = new Expense(date, value)之类的费用对象放入List<Object> list = new ArrayList<>();中,并添加了一些类似的日期费用,如

list.add(new Expense(23, 700);
list.add(new Expense(23, 900);
list.add(new Expense(23, 700);
list.add(new Expense(24, 500);
list.add(new Expense(29, 500);

现在,需要添加一天的所有相似日期费用。我该怎么办?

我尝试了下面列出的代码

List<Object> list = new ArrayList<>();
list.add(new Expense(23, 700);
list.add(new Expense(23, 900);
list.add(new Expense(23, 700);
list.add(new Expense(24, 500);
list.add(new Expense(29, 500);
for(int i = 0; i<list.size(); i++) {

 Expense expense1 = (Expense) list.get(i);
 if(expense1.getDate().equals(date)) {
      value += Float.valueOf(expense1.getValue());

 } else{
        value =0f;
        value = Float.valueOf(expense1.getValue());
 }

  date = expense1.getDate();
  Log.d("wdvfd234rsdf", expense1.getDate()+",  "+expense1.getValue());

}
answer of above example similar as, 
23 date = 1600
24 date = 500
29 date = 500

1 个答案:

答案 0 :(得分:2)

在Kotlin中,这非常简单(您可以在android应用中使用它):

name = models.IntegerField(choices=ALGORITHM_NAME)

输出将是:

fun main() {
    data class Expense(val date: Int, val amount: Int)

    val expenses = listOf(                                                     
        Expense(23, 700),
        Expense(23, 900),
        Expense(23, 700),
        Expense(24, 500),
        Expense(29, 500)
    )

    val dailyExpences = expenses
        .groupBy(Expense::date, Expense::amount)
        .map {Expense(it.key, it.value.sum())}

    println("Daily expences: $dailyExpences")
}