根据未来结果排序 [英] Sorting based on Future Result

查看:73
本文介绍了根据未来结果排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试按将来的布尔值对列表进行排序.

I've trying to sort a list by a future boolean.

我有一个ID列表,我需要查询一个外部服务以了解它们背​​后是否有上下文信息.我用于执行此操作的方法将返回可选的将来.

I have a list of IDs and I need to query an external service to find out if there's contextual information behind them. The method I use to do this returns an optional future.

我希望通过使用分区方法来创建两个ID列表,一个包含上下文信息,另一个不包含.

By using the partition method I hoped to create two lists of IDs, one with contextual information and one without.

此处的以下答案为此提供了很多帮助:

The following answer on here provided a lot of help for this: Scala - sort based on Future result predicate

我现在有一个未经测试的粗略方法,

I now have an rough, untested method that looks like so,

val futureMatch = listOfIds.map( b => b.map{ j =>
  getContext(j).map{ k =>
    Map( j -> k)
  }
}).map(Future.sequence(_)).flatMap(identity)

val partitionedList = futureMatch.map(_.partition{
  case (k, Some(v)) => true
  case _ => false
})

因此,按照另一个问题的建议,我试图将所有答案都保持在同一水平,然后使用Future.sequenceflatMap(identity)展平期货的嵌套层.

So as advised in the other question, I'm attempting to get all my answers at the same level, and then using Future.sequence and flatMap(identity) to flatten nested layers of futures.

问题在于,这并不十分有效.

The problem is this doesn't feel very efficient.

理想情况下,成功的列表将具有List[Map[String, String]]而不是List[Map[String, Option[String]]的签名,失败的列表将仅是字符串列表,因此只需要一维.按照目前的情况,我有两个相同的列表签名,但有些冗余.例如,在成功列表中,我知道这将存在,因此不必选择.

Ideally the successful list would have a signature of List[Map[String, String]] not List[Map[String, Option[String]] and the failed list would just be a list of Strings, so it'd only need to be one dimensional. As it currently stands I have two identical list signatures which have some redundancy. For example in the successful list, I know this is going exist so it doesn't need to be an option.

任何想法,我如何实现这种结构并生成两个具有不同签名的列表,即使这是最有效的方法.

Any ideas how I could achieve this structure and produce two lists with different signatures or even if this is the most efficient way.

谢谢.

查看分区的签名,看来我只能产生两个具有相同签名的列表,所以不同的签名可能要问的太多了.我想我以后可以整理一下清单.

Looking at the signature for partition it looks like I can only produce two lists of the same signature, so a different signature is probably too much to ask. I guess I can just flatten the list afterwards.

推荐答案

我在链接的问题的评论中也找到了合适的解决方案.

I found a suitable solution in the comments of the question I linked too.

val (matched, unmatched) =
  finalMatch.foldLeft(List.empty[Map[String, String]], List.empty[String]) {
     case ((matched, unmatched), p) => p match {
       case m:Map[String, String] => (m :: matched, unmatched)
       case s:String => (matched, s :: unmatched)
     }
   }

唯一的问题是它导致类型擦除.我打开了另一个问题来讨论这个问题.

The only issue with this is it leads to type erasure. I've opened another question to discuss this issue.

通过foldLeft处理类型擦除

谢谢.

这篇关于根据未来结果排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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