I'd like to iterate over an ArrayList of Strings:
List<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");
Instead of Iterating over all Items:
for(String a : list) {
System.out.println(a);
}
I'd like to exclude the last elements of the List. Currently I use:
for(int i = 0; i < list.size()-1; i++) {
System.out.println(list.get(i));
}
But I was wondering, if there is a shorter form. For example in R you could simply generate a list without the last element:
a = c("A", "B", "C")
a[-length(a)]
You could use list.subList(0,list.size()-1) to get a view of the List without the last element.
List<E>java.util.List.subList(int fromIndex, int toIndex)Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. (If fromIndex and toIndex are equal, the returned list is empty.) The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa. The returned list supports all of the optional list operations supported by this list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With