Java 如何从排序列表中获取第一个元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2503363/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I get a first element from a sorted list?
提问by Roman
I used Collections.sort(playersList);
to sort a List
. So, I think playersList
is sorted now. But how can I get the first element of the list? playersList[0]
does not work.
我曾经Collections.sort(playersList);
对一个List
. 所以,我认为playersList
现在已经排序了。但是我怎样才能得到列表的第一个元素呢?playersList[0]
不起作用。
采纳答案by Matthew Flaschen
playersList.get(0)
Java has limited operator polymorphism. So you use the get()
method on List
objects, not the array index operator ([]
)
Java 具有有限的运算符多态性。所以你get()
在List
对象上使用该方法,而不是数组索引运算符 ( []
)
回答by jjnguy
You have to access lists a little differently than arrays in Java. See the javadocsfor the List
interface for more information.
访问列表的方式与 Java 中的数组略有不同。请参阅的javadoc的List
接口以获取更多信息。
playersList.get(0)
However if you want to find the smallest element in playersList
, you shouldn't sort it and then get the first element. This runs very slowly compared to just searching once through the list to find the smallest element.
但是,如果要查找 中的最小元素playersList
,则不应对其进行排序然后获取第一个元素。与仅在列表中搜索一次以找到最小元素相比,这运行得非常慢。
For example:
例如:
int smallestIndex = 0;
for (int i = 1; i < playersList.size(); i++) {
if (playersList.get(i) < playersList.get(smallestIndex))
smallestIndex = i;
}
playersList.get(smallestIndex);
The above code will find the smallest element in O(n)
instead of O(n log n)
time.
上面的代码将在O(n)
而不是O(n log n)
时间中找到最小的元素。
回答by rsp
That depends on what type your list is, for ArrayList
use:
这取决于您的列表是什么类型,供ArrayList
使用:
list.get(0);
for LinkedList
use:
对于LinkedList
使用:
list.getFirst();
if you like the array
approach:
如果你喜欢这种array
方法:
list.toArray()[0];
回答by OscarRyz
Matthew's answeris correct:
马修的回答是正确的:
list.get(0);
To do what you tried:
做你尝试过的事情:
list[0];
you'll have to wait until Java 7 is released:
你必须等到Java 7 发布:
devoxx conference http://img718.imageshack.us/img718/11/capturadepantalla201003cg.png
devoxx 会议 http://img718.imageshack.us/img718/11/capturadepantalla201003cg.png
Here's an interesting presentationby Mark Reinhold about Java 7
这是Mark Reinhold 关于 Java 7的有趣演示
It looks like parleys site is currently down, try later :(
看来 parleys 站点目前已关闭,请稍后再试:(
回答by Steve Kuo
If your collection is not a List
(and thus you can't use get(int index)
), then you can use the iterator:
如果您的集合不是 a List
(因此您不能使用get(int index)
),那么您可以使用迭代器:
Iterator iter = collection.iterator();
if (iter.hasNext()) {
Object first = iter.next();
}
回答by polygenelubricants
If you just want to get the minimum of a list, instead of sorting it and then getting the first element (O(N log N)
), you can use do it in linear time using min
:
如果您只想获取列表的最小值,而不是对其进行排序然后获取第一个元素 ( O(N log N)
),您可以使用以下方法在线性时间内完成min
:
<T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll)
That looks gnarly at first, but looking at your previous questions, you have a List<String>
. In short: min
works on it.
起初看起来很粗糙,但看看你之前的问题,你有一个List<String>
. 简而言之:min
致力于它。
For the long answer: all that super
and extends
stuff in the generic type constraints is what Josh Bloch calls the PECS principle (usually presented next to a picture of Arnold -- I'M NOT KIDDING!)
对于长回答:所有super
与extends
东西在泛型类型的限制是什么乔希布洛赫调用佩奇原则(旁边通常呈现给阿诺德的照片-我不是在开玩笑!)
Producer Extends, Consumer Super
生产者扩展,消费者超级
It essentially makes generics more powerful, since the constraints are more flexible while still preserving type safety (see: what is the difference between ‘super' and ‘extends' in Java Generics)
它本质上使泛型更强大,因为约束更灵活,同时仍保留类型安全(请参阅:Java 泛型中的“超级”和“扩展”之间的区别是什么)
回答by svarog
Using Java 8 streams, you can turn your list into a stream and get the first item in a list using the .findFirst()
method.
使用 Java 8 流,您可以将列表转换为流并使用.findFirst()
方法获取列表中的第一项。
List<String> stringsList = Arrays.asList("zordon", "alpha", "tommy");
Optional<String> optional = stringsList.stream().findFirst();
optional.get(); // "zordon"
The .findFirst()
method will return an Optionalthat may or may not contain a string value (it may not contain a value if the stringsList
is empty).
该.findFirst()
方法将返回一个Optional,它可能包含也可能不包含字符串值(如果stringsList
为空,则它可能不包含值)。
Then to unwrap the item from the Optional use the .get()
method.
然后要从 Optional 中解开项目,请使用该.get()
方法。
回答by Cristopher Plasma
public class Main {
public static List<String> list = new ArrayList();
public static void main(String[] args) {
List<Integer> l = new ArrayList<>();
l.add(222);
l.add(100);
l.add(45);
l.add(415);
l.add(311);
l.sort(null);
System.out.println(l.get(0));
}
}
without l.sort(null) returned 222
没有 l.sort(null) 返回 222
with l.sort(null) returned 45
与 l.sort(null) 返回 45