Home
Java
ArrayList Every Nth Element
This page was last reviewed on Aug 10, 2023.
Dot Net Perls
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.
ArrayList
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.
Modulo
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.
Collections.addAll
Step 1 We create a new ArrayList, which will be where we place the elements that we wish to return.
Step 2 In this step we loop over the indexes of the ArrayList argument, using a for-loop.
for
Step 3 If the modulo division of the index by the "n" argument equals zero, we want to keep the element.
Step 4 We return the ArrayList result, which now contains the elements we decided to keep.
return
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.
This page was last updated on Aug 10, 2023 (new).
Home
Changes
© 2007-2024 Sam Allen.