Java Program To Square All Items In List
Chapter:
Miscellaneous
Last Updated:
17-05-2023 15:12:46 UTC
Program:
/* ............... START ............... */
import java.util.ArrayList;
import java.util.List;
public class SquareListItemsExample {
public static void main(String[] args) {
// Create a list
List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(5);
// Square all items in the list
for (int i = 0; i < numbers.size(); i++) {
int squared = numbers.get(i) * numbers.get(i);
numbers.set(i, squared);
}
// Print the squared list
System.out.println("Squared list: " + numbers);
}
}
/* ............... END ............... */
Output
Squared list: [1, 4, 9, 16, 25]
Notes:
-
In this example, we create an ArrayList called numbers and add some integer values to it.
- To square all items in the list, we use a for loop to iterate over each element. For each element, we retrieve its value using numbers.get(i), square it by multiplying it with itself, and store the squared value in a variable called squared. Then, we use the numbers.set(i, squared) method to update the element in the list with its squared value.
- After squaring all items in the list, we print the squared list using System.out.println(), which displays the squared list as [1, 4, 9, 16, 25].
- So, the program demonstrates how to square all items in a list by iterating over each element and updating it with its squared value in Java.