I am working on a program that has to display only the items in an ArrayList whose value is greater than 10. I am using the toString()
method to display the items, but I want to display only the items that have a value greater than 10. Any help would be greatly appreciated.
CodePudding user response:
You can use for loop with if condition to integer greater than 10 in an ArrayList
import java.util.*;
public class MyArrayList {
public static void main(String args[]) {
// Creating and initializing the ArrayList
// Declaring object of integer type
List<Integer> randomNumbers = Arrays.asList(1, 12, 33, 4, 25, 6, 17, 98);
// Iterating using for loop
for (int i = 0; i<randomNumbers.size(); i ) {
if (randomNumbers.get(i) > 10) {
// Printing and display the elements over 10
System.out.print(randomNumbers.get(i) " ");
}
}
}
}
CodePudding user response:
What type is the ArrayList? Is it already of type ArrayList<Integer>
?
In Java, an enhanced for-loop is a quite efficient way to read through the ArrayList:
for(single datatype : group of datatypes)
If numberList is type
ArrayList<Integer>
:for(Integer number : numberList)
If list is a non-typed
ArrayList
:for(Object obj : list)
Then in that loop, you can use the >
(greater than) operator to test the value of each number read. As shown in @Sumit Sharma's example:
if (randomNumbers.get(i) > 10)
-- Note: this is the syntax for a regular, not the enhanced for-loop
EDIT FOR ADDITIONAL INFORMATION
This is what the enhanced for-loop translated into the style of a regular for-loop
for(int index = 0; index < (size of the datatype group); index )
It is class Array List with 2 items in it that of name and the number -- @Grenard
Depending on which index it is, you can perform a test like this:
/*
With the regular for-loop:
get the whole ArrayList entry and read the Integer value
*/
Object testObject = groupOfDatatypes.get("the for-loop index");
Integer testInt = testObject.get("the object's integer index");
/*
With the enhanced for-loop:
it already knows its index, use that to read the Integer value
*/
Integer testInt = datatype.get("the object's integer index");
Note: This is pseudo-code to the max