具有Java 8强大功能的String上的特殊顺序 [英] Special order on String with the power of Java 8

查看:178
本文介绍了具有Java 8强大功能的String上的特殊顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个有限的字符串列表(或数组)。此列表将通过以下方式描述我的新订单:字符串 s1 小于字符串 s2 iff之一接下来的三个语句成立

I've got a finite list (or array) of strings. This list shall describe my new order by the following means: A string s1 is less than a string s2 iff one of the next three statements holds


  • 两者都在列表中 s1 有较低的列表中的索引比 s2

  • 两者都不在列表中, s1 小于 s2 按字符串的自然顺序

  • s1 在列表中, s2 不是

  • both are in the list an s1 has a lower index in the list than s2
  • both aren't in the list and s1 is less than s2 by the natural order on strings
  • s1 is in the list and s2 is not

我想用的是电源Java 8编写一行Comparator。什么是最短的这条线?您可以假设我的列表是 ArrayList< String>

I want to use the power of Java 8 to write a one line Comparator. What is the shortest such line? You can assume my list to be an ArrayList<String>.

编辑:我不想订购我正在谈论的清单。我想使用该列表来定义一个允许我订购许多其他列表的订单。

I don't want to order the list I'm talking about. I want to use that list to define an order which allows me to order many other lists.

推荐答案

最短的比较器您可以获得的任务定义是:

The shortest Comparator definition you can get for your task is:

Comparator.comparingInt((String s) -> reference.indexOf(s)+Integer.MIN_VALUE)
          .thenComparing(Comparator.naturalOrder())

但它要求读者理解整数比较中的 + Integer.MIN_VALUE 习语。它基本上意味着执行无符号比较(另见 Integer.compareUnsigned(...) ),以便 -1 的值,由<返回对于缺席值,code> List.indexOf 被视为最高可能的数字,因此当前值的每个索引都被认为小于该值,以满足您的规范。

but it requires the reader to understand the +Integer.MIN_VALUE idiom in integer comparisons. It basically means "perform an unsigned comparison" (see also Integer.compareUnsigned(…)), so that the value -1, returned by List.indexOf for absent values, is treated as the highest possible number, so that every index of a present value is considered to be smaller than that, to meet your specification.

然后,您可以简单地链接另一个比较器,这里是自然顺序,对于两个索引都相同的情况,包括两者都不存在的可能性。

Then, you can simply chain another comparator, here the natural order, for the case both indices are the same, which includes the possibility that both are absent.

如果您认为读者难以理解无符号比较,则必须明确编码三种情况,如 tobias_k的回答

If you think that the unsigned comparison is to hard to grasp for the reader, you have to encode your three cases explicitly, as already shown in tobias_k’s answer.

这篇关于具有Java 8强大功能的String上的特殊顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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