首页 \ 问答 \ 将番石榴范围转换为不同类型(Transform a Guava Range to a Different Type)

将番石榴范围转换为不同类型(Transform a Guava Range to a Different Type)

如何将一种类型的给定Guava Range转换为另一种类型的范围。

我期待一种类似于Predicates.compose的compose方法。 以Integer和Long为例:

Range<Integer> intRange = Range.compose(Range.atLeast(10l),integerFromLongFunction);

我写了撰写方法:

    public static <F extends Comparable<F>, T extends Comparable<T>> Range<T> compose(Range<F> range,
        Function<F, T> function) {
    Range<T> result;
    if (range.hasUpperBound() && range.hasLowerBound()) {
        T upperEndpoint = function.apply(range.upperEndpoint());
        T lowerEndpoint = function.apply(range.lowerEndpoint());
        result = Range.range(lowerEndpoint, range.lowerBoundType(), upperEndpoint, range.upperBoundType());
    } else if (range.hasUpperBound()) {
        result = Range.upTo(function.apply(range.upperEndpoint()), range.upperBoundType());
    } else if (range.hasLowerBound()) {
        result = Range.downTo(function.apply(range.lowerEndpoint()), range.lowerBoundType());
    } else {
        result = Range.all();
    }
    return result;
}

单元测试:

@Test
public void testLongRangeToInteger() {
    Integer inRange = 6;
    Integer outOfRange = 3;
    Range<Long> longRange = Range.atLeast(5l);
    assertTrue(longRange.apply(inRange.longValue()));
    assertFalse(longRange.apply(outOfRange.longValue()));

    Function<Long, Integer> function = integerFromLongFunction();
    Range<Integer> intRange = RangeExtended.compose(longRange, function);
    assertTrue(intRange.apply(inRange));
    assertFalse(intRange.apply(outOfRange));
}

public static Function<Long, Integer> integerFromLongFunction() {
    return new Function<Long, Integer>() {

        @Override
        public Integer apply(Long input) {
            return (input == null) ? null : input.intValue();
        }
    };
}

我目前的愿望实际上是将Joda Duration转换为相应的millis,但为了简单起见,我在Long / Integer中编写了这个例子。

似乎Guava会有这个,但我找不到任何地方。 我正在使用v14,但是查看最新的v17 javadoc没有暴露任何东西。


How do I transform a given Guava Range of one type to a range of another type.

I expect a compose method similar to Predicates.compose. Take Integer and Long for example:

Range<Integer> intRange = Range.compose(Range.atLeast(10l),integerFromLongFunction);

I wrote the compose method:

    public static <F extends Comparable<F>, T extends Comparable<T>> Range<T> compose(Range<F> range,
        Function<F, T> function) {
    Range<T> result;
    if (range.hasUpperBound() && range.hasLowerBound()) {
        T upperEndpoint = function.apply(range.upperEndpoint());
        T lowerEndpoint = function.apply(range.lowerEndpoint());
        result = Range.range(lowerEndpoint, range.lowerBoundType(), upperEndpoint, range.upperBoundType());
    } else if (range.hasUpperBound()) {
        result = Range.upTo(function.apply(range.upperEndpoint()), range.upperBoundType());
    } else if (range.hasLowerBound()) {
        result = Range.downTo(function.apply(range.lowerEndpoint()), range.lowerBoundType());
    } else {
        result = Range.all();
    }
    return result;
}

with the Unit Test:

@Test
public void testLongRangeToInteger() {
    Integer inRange = 6;
    Integer outOfRange = 3;
    Range<Long> longRange = Range.atLeast(5l);
    assertTrue(longRange.apply(inRange.longValue()));
    assertFalse(longRange.apply(outOfRange.longValue()));

    Function<Long, Integer> function = integerFromLongFunction();
    Range<Integer> intRange = RangeExtended.compose(longRange, function);
    assertTrue(intRange.apply(inRange));
    assertFalse(intRange.apply(outOfRange));
}

public static Function<Long, Integer> integerFromLongFunction() {
    return new Function<Long, Integer>() {

        @Override
        public Integer apply(Long input) {
            return (input == null) ? null : input.intValue();
        }
    };
}

My current desire is actually to convert a Joda Duration to it's corresponding millis, but I wrote the example in Long/Integer for simplicity.

It seems that Guava would have this, but I can't find anywhere. I'm using v14, but looking at the latest v17 javadoc didn't expose anything.


原文:https://stackoverflow.com/questions/24889243
更新时间:2024-01-16 18:01

最满意答案

在光标上调用toArray而不是forEach

var a = db.my_collection.find(
    {timestamp : {$gt: 1343032491799}}, {_id:0,sid:1}).limit(20)
    .toArray().map(function(o){return o.sid;})

UPDATE

似乎您可以跳过toArray并直接转到map因为光标直接提供了该方法:

var a = db.my_collection.find(
    {timestamp : {$gt: 1343032491799}}, {_id:0,sid:1}).limit(20)
    .map(function(o){return o.sid;})

Call toArray on the cursor instead of forEach:

var a = db.my_collection.find(
    {timestamp : {$gt: 1343032491799}}, {_id:0,sid:1}).limit(20)
    .toArray().map(function(o){return o.sid;})

UPDATE

Seems you can skip the toArray and go right to the map as the cursor provides that method directly:

var a = db.my_collection.find(
    {timestamp : {$gt: 1343032491799}}, {_id:0,sid:1}).limit(20)
    .map(function(o){return o.sid;})

相关问答

更多
  • 在光标上调用toArray而不是forEach : var a = db.my_collection.find( {timestamp : {$gt: 1343032491799}}, {_id:0,sid:1}).limit(20) .toArray().map(function(o){return o.sid;}) UPDATE 似乎您可以跳过toArray并直接转到map因为光标直接提供了该方法: var a = db.my_collection.find( {timesta ...
  • $file = fopen("contacts.csv","w"); foreach ($data as $record){ $contact = iterator_to_array($record); fputcsv($file,$contact); } 此解决方案在$ data保留游标时起作用,并且循环内的iterator_to_array()将单个记录转换为数组以放置在CSV文件中。 $file = fopen("contacts.csv","w"); ...
  • 据我所知: "A group is considered "large" if the cumulative value of its elements is above a given threshold." 我建议编写一个规则来执行insertLogical(参见“Truth Maintenance”)的辅助事实,将该组标记为“大”。 这应该简化“大”群体的积累。 (对不起,我编辑了将怪物名称减少到可读性。) As far as I have understood this: "A group is ...
  • 我可以建议你两种方法来完成你的任务。 简单的方法。 当您开始下载请求时,将updatedFilesCouter设置为-1。 在任何操作结束时,您需要进行比较并添加或替换updatedFilesCouter。 如果第一个操作要更改updatedFilesCouter,您可以注意到您的值始终为-1,因此您需要替换它。 如果第二个操作要更改updatedFilesCouter,那么它的值总是不同于-1,因此您需要添加新值。 因此,如果第一个操作有2个更新文件而第二个操作有3个,那么最后你将得到5个,你可以找出哪个 ...
  • 这段代码 for (int x = 0; x < list.Count(); x++) { int pos = list.IndexOf(player.play.pId); playerPoints = numPlayers - pos; } 将在for循环完成后每次分配变量playerPoints ,它将具有list最后一项的值 我认为你需要类似的东西 playerPoints = 0; fo ...
  • 您可以使用强制转换为必需的方法实现(在您的情况下是Iterable接口中的那个): documentList.forEach((Consumer) (Document document) -> { System.out.println(document.toJson()); }); 奇怪的是Spring Tools Suite没有显示错误,同时IntelliJ Idea会显示错误,它显示“模糊方法调用”:) you can use casting to requ ...
  • 这两个语句在核心API级别基本相同,即获取光标并转换结果。 然而,性能有一个“核心”差异: .forEach()将“一次一个”转换游标结果并处理它提供的迭代器函数。 .fetch()从光标“一次性”获取“数组”,这意味着它在一次命中中都是“内存中”。 所以无论如何,在从查询的光标获取“核心”操作时,实际上“更快”。 但是,不评估每个游标迭代的“表达式”可能会“稍微快一点”,因此.fetch()可能在这里赢得“小”。 当然,最大的问题是“现在一切都在记忆中”,因此需要考虑“开销”。 同样,在.fetch() ...
  • Mongo shell是一个JavaScript shell,因此支持大多数标准JavaScript方法。 您可以像在JavaScript中的任何常规对象上一样检查属性是否存在 - 使用hasOwnProperty()方法: db.testData.find({}).forEach(function(x){ if (x.hasOwnProperty('name')) { // Do something } }) Mongo shell is a JavaScript she ...
  • foreach的定义类似于: final def foreach(f: (A) ⇒ Unit): Unit f :应用于每个元素的副作用的函数。 函数f的结果被丢弃 Scala中的foreach通常用于表示涉及副作用的函数的用法,例如打印到STDOUT。 如果您想通过应用特定功能返回某些内容,则必须使用map final def map[B](f: (A) ⇒ B): List[B] 我从List的文档中复制了语法,但它对于RDD也是类似的。 正如你所看到的,它在数据类型A上运行函数f并返回一 ...
  • 如果您要更新整个集合,那么在当前代码中的光标limit就没有必要了。 您收到的错误是因为products集合中的mappingData字段没有名为array的子文档字段。 从问题中的示例中,只有title子文档字段可用,这就是您想要的字段。 根据产品集合的大小,将转换后的文档插入新集合可能会影响您的操作。 通过使用新的无序批量插入API ,您可以避免缓慢的插入性能,通过批量发送插入操作来简化您的插入操作,甚至更好地为您提供有关成功和失败的真实反馈。 以下批量插入API操作将插入newcollection所需 ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)