Nth element. Suppose we want to sample the elements in an ArrayList by only processing every other element. In Java 20 we can develop an efficient method to perform this task.
By testing the indexes with modulo, we can determine if an element needs to be added to the result array. This gives us every Nth element in an ArrayList.
Example. To begin, we create an array and add it to an ArrayList in main(). In the EveryNthElement method, we have a series of logical steps we perform.
import java.util.ArrayList;
import java.util.Collections;
public class Program {
static ArrayList<String> EveryNthElement(ArrayList<String> list, int n) {
// Step 1: create new result ArrayList.
ArrayList<String> result = new ArrayList<>();
// Step 2: loop over indexes in the input ArrayList.
for (int i = 0; i < list.size(); i++) {
// Step 3: use a modulo expression and add the element.
if ((i % n) == 0) {
result.add(list.get(i));
}
}
// Step 4: return the new ArrayList.
return result;
}
public static void main(String[] args) {
// Use method on this ArrayList.
String[] array = { "a", "b", "c", "d", "e", "f", "g", "h", "i" };
ArrayList<String> test = new ArrayList<>();
Collections.addAll(test, array);
ArrayList<String> result = EveryNthElement(test, 2);
System.out.println(String.join(",", result));
ArrayList<String> result2 = EveryNthElement(test, 3);
System.out.println(String.join(",", result2));
}
}a,c,e,g,i
a,d,g
In the results, it is easy to tell that the logic is correct. With an argument of 2, every other element is kept. With an argument of 3, meanwhile, we skip over 2 elements before keeping one.
To summarize, it is possible to develop a method that processes elements in an ArrayList based on their indexes. With modulo, we can determine which elements to retain.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.