将列表中的项目分组并汇总所有其他字段Android,在recyclerview中显示结果

时间:2019-12-13 23:18:24

标签: java android android-recyclerview java-8 java-stream

我有一个具有此结构的Firebase数据库

{
  "foo" : {
    "data" : {
      "2019-12-01" : [ {
        "item1" : 8,
        "item2" : 16,
        "name" : "user1"
      }, {
        "item1" : 9,
        "item2" : 18,
        "name" : "user2"
      } ],
      "2019-12-02" : [ {
        "item1" : 2,
        "item2" : 26,
        "name" : "user1"
      }, {
        "item1" : 6,
        "item2" : 6,
        "name" : "user2"
      } ]
    }
  }
}

我以一种非常简单的方式在主要活动中填充recyclerviewer

public class MainActivity extends AppCompatActivity {

    RecyclerView recyclerView;

    private RecyclerView.LayoutManager layoutManager;
    private Adapter adapter;

    final List<Model> tempList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        recyclerView = findViewById(R.id.simpleRecycler);

        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setHasFixedSize(true);

        Query statsRef = FirebaseDatabase.getInstance()
                .getReference("foo")
                .child("data")
                .orderByKey()
                .startAt("2019-12-01")
                .endAt("2019-12-02");

        // Read from the database
        statsRef.addValueEventListener(new ValueEventListener() {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                for (DataSnapshot itemSnapshot : dataSnapshot.getChildren()){
                    for (int i = 0; i < 2; i++) {
                        Model model = itemSnapshot.child(String.valueOf(i)).getValue(Model.class);
                        tempList.add(model);
                    }
                }

                adapter = new Adapter(tempList);
                recyclerView.setAdapter(adapter);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
            }
        });
    }
}

适配器是:

public class Adapter extends RecyclerView.Adapter {

    List<Model> models;

    public Adapter(List<Model> models) {
        this.models = models;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.simple_row, parent, false);

        return new ViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        ViewHolder vh = (ViewHolder)holder;

        vh.name.setText(models.get(position).getName());
        vh.item1.setText(String.valueOf(models.get(position).getItem1()));
        vh.item2.setText(String.valueOf(models.get(position).getItem2()));
    }

    @Override
    public int getItemCount() {
        return models.size();
    }
}

结果是一个像这样的表:

+-------+---+----+
| user1 | 8 | 16 |
+-------+---+----+
| user2 | 9 | 18 |
+-------+---+----+
| user1 | 2 | 26 |
+-------+---+----+
| user2 | 6 |  6 |
+-------+---+----+

问题是我想按名称对列表进行分组,然后对所有其他相对字段进行如下求和

+-------+----+----+
| user1 | 10 | 42 |
+-------+----+----+
| user2 | 15 | 24 |
+-------+----+----+

我尝试没有成功:

tempList.stream().collect(Collectors.groupingBy(Model::getName))
                    .entrySet().stream()
                    .collect(Collectors.toMap(x -> {
                        int item1 = x.getValue().stream().mapToInt(Model::getItem1).sum();
                        int item2 = x.getValue().stream().mapToInt(Model::getItem2).sum();

                        return new Model(x.getKey(), item1, item2);

                    }, Map.Entry::getValue));

在将适配器设置为recyclerviewer之前,我已经在上面添加了以上代码。

有什么帮助吗?

1 个答案:

答案 0 :(得分:5)

您可以对定义的Collectors.toMap使用mergeFunction操作来执行聚合,例如:

List<Model> output = new ArrayList<>(tempList.stream()
        .collect(Collectors.toMap(Model::getName, Function.identity(),
                Model::mergeSimilarNames))
        .values()); // interested in merged output 

其中合并功能可以在Model类中定义为:

static Model mergeSimilarNames(Model one, Model two) {
    return new Model(one.getName(), one.getItem1() + two.getItem1(), one.getItem2() + two.getItem2());
}

要将其与您现有的方法相关联,需要在对元素进行分组之后进行归约运算,例如:

Map<String, Optional<Model>> grouping = tempList.stream()
        .collect(Collectors.groupingBy(Model::getName,
                Collectors.reducing(Model::mergeSimilarNames)));

但是您只希望获得最终视图,即List<Model>上方的值中的Map,因此在这种情况下,您得到的代码将是:

List<Model> output = tempList.stream()
        .collect(Collectors.groupingBy(Model::getName,
                Collectors.reducing(Model::mergeSimilarNames)))
        .values().stream()
        .filter(Optional::isPresent)
        .map(Optional::get)
        .collect(Collectors.toList());

但请注意,toMap(f1,f2,f3) is preferred over groupingBy(f1, reducing(f2,f3))