如何在rx java中分组和返回列表 [英] How to group by and return list in rx java

查看:20
本文介绍了如何在rx java中分组和返回列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据 Rxjava 中的某些条件创建组列表.

I'm trying to create group list based on certain conditions in Rxjava.

以下是我的回复:

{  
   "dates":[  
      {  
         "date":18,
         "value":"1"
      },
      {  
         "date":18,
         "value":"2"
      },
      {  
         "date":18,
         "value":"3"
      },
      {  
         "date":19,
         "value":"1"
      },
      {  
         "date":19,
         "value":"2"
      },
      {  
         "date":19,
         "value":"3"
      },
      {  
         "date":19,
         "value":"4"
      }
   ]
}

如何按值 18 分组 [值 1,值 2,值 3,最高值 = 3,最低值 = 1]19[value 1, value 2, value 3, value 4,highestvalue= 4, minimumvalue = 1] 使用 Rxjava

How can group by the values 18 [value 1, value 2, value 3, highestvalue= 3, lowestvalue = 1] 19[value 1, value 2, value 3, value 4,highestvalue= 4, lowestvalue = 1] using Rxjava

注意:我可以使用 for 循环创建,但响应将从服务器获取,并且因为它返回使用 rx java 功能的可观察想法.

Note: I can create using for loop but the response will be fetched from the server and since it is returning observable thought of using rx java functionality.

任何帮助将不胜感激.

谢谢,山地

推荐答案

查看 group by 功能.

以下是任何好奇的人的示例:

Here's the example for anyone who's curious:

class DateModel implements Comparable<DateModel>{
    Integer date;
    Integer value;

    public DateModel(int date, int value){
        this.date = date; 
        this.value = value;
    }

    @Override
    public int compareTo(DateModel o) {
        return value.compareTo(o.value);
    }
}

然后,如果我们必须聚合这些模型对象的列表:

And then if we have to aggregate a list of these model objects:

// example list
List<DateModel> dateList = Arrays.asList(
  new DateModel(18,1),
  new DateModel(18,2),
  new DateModel(18,3),
  new DateModel(19,1),
  new DateModel(19,2),
  new DateModel(19,3),
  new DateModel(19,4)
);

// the following observable will give you an emission for every grouping
// for the example data above, you should get two emissions (group 18 and 19)
Observable<PriorityQueue<DateModel>> observable = 
  Observable.from(dateList)
    .groupBy(dateModel -> dateModel.date)
    .flatMap(groups -> groups.collect(PriorityQueue::new, PriorityQueue::add));

PriorityQueue 只是用于收集的结构示例.如果您从队列中弹出,您将得到 18-1、18-2、18-3 等(按照您要求的顺序).您可以使用不同的结构来仅找到最大值 &分钟

PriorityQueue was just an example of the structure used for collecting. If you pop from queue, you'll get 18-1, 18-2, 18-3 etc (in the order you asked). You can use a different structure for the purposes of only finding the max & min.

这篇关于如何在rx java中分组和返回列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆