如何获取集合中一个元素前面和后面的第1个元素(Java)

huangapple go评论111阅读模式
英文:

How to get the 1 element before & after an element in a set (Java)

问题

给定一组字符串(1.0 1.1 1.2 3.0 3.1 4.0),我希望能够获取特定项前面的1个元素和后面的1个元素。

例如:

1.0 --> 1.1
1.1 --> 1.0, 1.2
1.2 --> 1.1, 3.0
4.0 --> 3.1

我具体使用了一个NavigableSet<String>,但理论上可以根据需要更改为更合适的数据结构。

英文:

Given a set of strings (1.0 1.1 1.2 3.0 3.1 4.0), I want to be able to get the 1 element before and the 1 element after a specific item.

For example:

1.0 --> 1.1
1.1 --> 1.0, 1.2
1.2 --> 1.1, 3.0
4.0 --> 3.1

I specifically have a NavigableSet<String> here, but in theory could change this to a better fit, if there is one.

答案1

得分: 2

你需要方法lower()和higher();

英文:

you need methods lower() and higher();

答案2

得分: 2

使用 NavigableSet#higher 来获取严格大于特定元素的第一个元素(即下一个元素),并使用 NavigableSet#lower 来获取严格小于某个元素的第一个元素(即前一个元素)。如果集合中没有这样的元素,这两个方法都会返回 null

System.out.println(set.higher("1.0"));// "1.1"
System.out.println(set.lower("1.0"));// null

演示链接!

英文:

Use NavigableSet#higher to get the first element strictly greater than a particular one (i.e., the next element) and NavigableSet#lower to get the first element strictly less than some element (i.e., the previous element). Both of these methods return null if there is no such element in the set.

System.out.println(set.higher("1.0"));//"1.1"
System.out.println(set.lower("1.0"));//null

Demo!

huangapple
  • 本文由 发表于 2020年7月22日 02:15:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/63020676.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定