9个解决方案
237 votes
请参阅javadoc
列表
list.get(0);
或设置
set.iterator().next();
并通过调用isEmpty()检查大小,然后再使用上述方法
!list_or_set.isEmpty()
stacker answered 2019-03-11T10:08:20Z
215 votes
Collection c;
Iterator iter = c.iterator();
Object first = iter.next();
(这是你最接近Set的“第一”元素。你应该意识到它对Set的大多数实现绝对没有意义。这可能对LinkedHashSet和TreeSet有意义,但对HashSet没有意义。)
bdares answered 2019-03-11T10:07:36Z
83 votes
在Java> = 8中,您还可以使用Streaming API:
Optional first = set.stream().findFirst();
(如果Set / List可能为空,则有用。)
Sonson123 answered 2019-03-11T10:08:51Z
17 votes
我很惊讶没有人建议番石榴解决方案:
com.google.common.collect.Iterables.get(collection, 0)
// or
com.google.common.collect.Iterables.get(collection, 0, defaultValue)
// or
com.google.common.collect.Iterables.getFirst(collection, defaultValue)
或者如果您期望单个元素:
com.google.common.collect.Iterables.getOnlyElement(collection, defaultValue)
// or
com.google.common.collect.Iterables.getOnlyElement(collection)
Radek Postołowicz answered 2019-03-11T10:09:23Z
13 votes
假设您有第一个项目的first。
有几种方法可以做到这一点:
Java(8之前):
String firstElement = null;
if (!strings.isEmpty() && strings.size() > 0) {
firstElement = strings.get(0);
}
Java 8:
Optional firstElement = strings.stream().findFirst();
番石榴
String firstElement = Iterables.getFirst(strings, null);
Apache commons(4+)
String firstElement = (String) IteratorUtils.get(strings, 0);
Apache公共(4之前)
String firstElement = (String) CollectionUtils.get(strings, 0);
随后或封装在适当的检查或try-catch块中。
科特林:
在Kotlin中,数组和大多数集合(例如:List)都有一个first方法调用。所以你的代码看起来像这样
列表:
val stringsList: List = listOf("a", "b", null)
val first: String? = stringsList.first()
对于数组:
val stringArray: Array = arrayOf("a", "b", null)
val first: String? = stringArray.first()
Ch Vas answered 2019-03-11T10:10:49Z
10 votes
组
set.toArray()[0];
名单
list.get(0);
Vasil Valchev answered 2019-03-11T10:11:12Z
6 votes
这不是这个问题的精确答案,但是如果对象应该排序,SortedSet有一个first()方法:
SortedSet sortedSet = new TreeSet();
sortedSet.add("2");
sortedSet.add("1");
sortedSet.add("3");
String first = sortedSet.first(); //first="1"
排序的对象必须实现Comparable接口(就像String一样)
molholm answered 2019-03-11T10:11:44Z
4 votes
java8等等
Set set = new TreeSet<>();
set.add("2");
set.add("1");
set.add("3");
String first = set.stream().findFirst().get();
这将帮助您检索列表或集的第一个元素。鉴于set或list不为空(orElse() on empty optional将抛出java.util.NoSuchElementException)
orElse()可以用作:(这只是一个解决方法 - 不推荐)
String first = set.stream().findFirst().orElse("");
set.removeIf(String::isEmpty);
以下是适当的方法:
Optional firstString = set.stream().findFirst();
if(firstString.isPresent()){
String first = firstString.get();
}
类似地,可以检索列表的第一个元素。
希望这可以帮助。
Nisarg Patil answered 2019-03-11T10:12:39Z
2 votes
您可以使用get(index)方法从List访问元素。
根据定义,集合只包含元素并且没有特定的顺序。 因此,没有“first”元素可以获得,但可以使用迭代器(使用for each循环)迭代它或使用toArray()方法将其转换为数组。
Feni answered 2019-03-11T10:13:12Z