最小/最大功能,具有两个可比性 [英] Min / Max function with two Comparable

查看:67
本文介绍了最小/最大功能,具有两个可比性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码段:

  Comparable< C> a = ...; 
可比较的< C> b = ...;
可比较的< C> min = a.compareTo(b)< = 0? a:b;

这类似于 Math.min(a,b),但在 Comparable 上定义。



我知道三元运算符已经很短了,但是我无法内嵌 a b ,我认为 min(a,b)是。 max(a,b)更容易理解。



我知道有多个流响应。集合函数的一组值,例如:

  Stream.of(a,b).min(Comparator.naturalOrder()) 

这将有助于内联表达式,但我仍然觉得它很难阅读并且有点太多



目前我正在使用自己的效用函数,但我很感兴趣:



如何以可读性和独立于库的方式找到两个可比对象中的最小值,而又没有太多的性能开销?

解决方案


  1. 来自 java.util.Collections Collections.max() Collections.min()

      Comparable< C> a = ...; 
    可比较的< C> b = ...;
    可比较的< C> min = Collections.min(Arrays.asList(a,b));







< ol start = 2>
  • 来自 org.apache.commons.lang3.ObjectUtils ObjectUtils.max() ObjectUtils.min()

      Comparable< C> a = ...; 
    可比较的< C> b = ...;
    可比较的< C> min = ObjectUtils.min(a,b);


  • Apache Commons开销较小,能够处理 null 值,但这是第三方库。


    I've got the following snippet:

    Comparable<C> a = ...;
    Comparable<C> b = ...;
    Comparable<C> min = a.compareTo(b) <= 0 ? a : b;
    

    This is similar to Math.min(a, b), but defined on Comparable.

    I know that the ternary operator is already quite short, but I can't inline the expressions for a and b and I think that min(a, b) resp. max(a, b) is easier to understand.

    I know that there are several stream resp. collection functions for a set of values like:

    Stream.of(a, b).min(Comparator.naturalOrder())
    

    This would help to inline the expressions, but I still find it difficult to read and a bit too much overhead for such a small task.

    For the moment I'm using my own utility function, but I'm interested:

    How to find the minimum of two Comparables in a readable and library independent manner without too much performance overhead?

    解决方案

    1. From java.util.Collections: Collections.max() and Collections.min()

      Comparable<C> a = ...;
      Comparable<C> b = ...;
      Comparable<C> min = Collections.min(Arrays.asList(a,b));
      


    1. From org.apache.commons.lang3.ObjectUtils : ObjectUtils.max() and ObjectUtils.min()

      Comparable<C> a = ...;
      Comparable<C> b = ...;
      Comparable<C> min = ObjectUtils.min(a, b);
      

    Apache Commons has less overhead and is able to handle null values, but it is a third party library.

    这篇关于最小/最大功能,具有两个可比性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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