See the javadoc
of List
list.get(0);
or Set
set.iterator().next();
and check the size before using the above methods by invoking isEmpty()
!list_or_set.isEmpty()
Answer from stacker on Stack OverflowSee the javadoc
of List
list.get(0);
or Set
set.iterator().next();
and check the size before using the above methods by invoking isEmpty()
!list_or_set.isEmpty()
Collection c;
Iterator iter = c.iterator();
Object first = iter.next();
(This is the closest you'll get to having the "first" element of a Set. You should realize that it has absolutely no meaning for most implementations of Set. This may have meaning for LinkedHashSet and TreeSet, but not for HashSet.)
playersList.get(0)
Java has limited operator polymorphism. So you use the get() method on List objects, not the array index operator ([])
You have to access lists a little differently than arrays in Java. See the javadocs for the List interface for more information.
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.
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.
Assuming the List inside your Optional can be empty, then you should account for this case as well. The easiest would thus be:
return persons.flatMap(list -> list.stream().findFirst()).map(Person::getAge).orElse(null);
This unfortunately does not handle a null first list entry as findFirst() throws a NullPointerException when the first element of a Stream is null (as Holger noted in the comments).
So if you want to skip null list entries and take the first non-null one, do as follows:
return persons.flatMap(list -> list.stream().filter(Objects::nonNull).findFirst())
.map(Person::getAge)
.orElse(null);
Otherwise, if instead you always want the first entry even when it is null, you could adapt it like this:
return persons.flatMap(list -> list.stream().limit(1).filter(Objects::nonNull).findFirst())
.map(Person::getAge)
.orElse(null);
however this really becomes quite convoluted, so it is simpler to just get back to testing whether the list is empty:
return persons.filter(list -> !list.isEmpty())
.map(list -> list.get(0))
.map(Person::getAge)
.orElse(null);
return null won't compile if int is the return type. Assuming you want an absent Optional<Integer> instead,
return persons.map(list -> list.get(0)).map(Person::getAge)
will work (unfortunately, there's no mapToInt returning OptionalInt like for streams). Two maps are needed to handle
Missing from the code - null check for the first element of the list. Would like to have this check as well.
This means that the element at index 2 (which is the 3rd element) is null. Iterating collections is usually done with the for-each loop:
for (Hotel hotel : hotels) {
// do something with each hotel
}
List, like many other things, in Java are zero-based. If the List is of size 2 then getHotels.get(0) and getHotels.get(1) return the first and second elements in the list.
You can use the following by using Optional and Streams.
StudentCollection sc = ...;
final Optional<Student> student = Optional.ofNullable(sc)
.map(StudentCollection::getStudents)
.map(Collection::stream)
.flatMap(Stream::findFirst);
The optional is used to safely handle the StudentCollection or the List<Student> which might by null.
As mentioned in the comment by @GhostCat the overhead created by above snippet is horribly big. Because you're using quite expensive API-methods for such a simple task.
As @Holger suggested, you can reduce the overhead by not using the Stream-API:
StudentCollection sc = ...;
final Optional<Student> student = Optional.ofNullable(sc)
.map(StudentCollection::getStudents)
.filter(list -> !list.isEmpty())
.map(list -> list.get(0));
Which still yields the same result as the prior snippet.
When you don't want any overhead you can use the following "old" (pre Java8) way:
StudentCollection sc = ...;
Student student = null;
if(sc != null){
List<Student> students = sc.getStudents();
if(students != null && !students.isEmpty()){
student = students.get(0);
}
}
The best code is the one which best expresses the intention of the developer. With this in mind, I would simply go for:
return yourStudentCollection != null &&
yourStudentCollection.getStudents() != null &&
!yourStudentCollection.getStudents().isEmpty() ?
yourStudentCollection.getStudents().get(0) :
null;
This is a good fit for Optional, though. I would return an Optional<Student>:
return Optional.ofNullable(yourStudentCollection)
.map(sc -> sc.getStudents())
.filter(s -> !s.isEmpty())
.map(s -> s.get(0));
import java.util.List;
import java.util.stream.Collectors;
public class Application {
public static void main(String[] args) {
List<List<String>> list = List.of(List.of("A1","B1"),List.of("A2","B2"));
List<String> listOnlyFirstOne = list
.stream() // create a stream
.map(subList -> subList.get(0)) // collect only first one of each list
.collect(Collectors.toList()); // collect result from map into new list
listOnlyFirstOne.forEach(System.out::println); // print new list
}
}
List<String> listViewTitle = new ArrayList<>();
listView.forEach(sublist -> listViewTitle.add(sublist.get(0)));
An easy way is the use of the stream api:
List firstElements = list.stream().map(o -> o[0]).collect(Collectors.toList());
It is as simple as using map and collect.
private void test(String[] args) {
List<Animal> list = new ArrayList<>();
list.add(new Animal("dog",11));
list.add(new Animal("cat",22));
List<String> names = list.stream()
// Animal -> animal.type.
.map(a -> a.getType())
// Collect into a list.
.collect(Collectors.toList());
System.out.println(names);
}
I used Animal as:
class Animal {
final String type;
final int age;
public Animal(String type, int age) {
this.type = type;
this.age = age;
}
public String getType() {
return type;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return "Animal{" +
"type='" + type + '\'' +
", age=" + age +
'}';
}
}