Skip to content

Loop through an Arraylist and show objects that fills the conditions Java

I have certain objects stored in an ArrayList. Every object has 5 variables (two strings, two ints and a double).

The method I’m trying to write will ask the user to input a value (double). It will then show all the objects in the ArrayList with a double that is equal or bigger than the user input double.

I’ve been trying to this with a for: each loop, but I don’t know how to add any conditions to it so that I get the results that I seek.

Any tips on how to sort through an ArrayList like this would be very great, I’m really stuck. The arrayList is called listOfthings and contains String nam, String bread, int alt, int wegtt and double townLength (this is the value I want it to use as a condition) This is the code I have so far:

public void sortmogs() {
        System.out.println("Smallest thing to display?>");
        listTownLength = Input.readInt();
        for (Mog mog : listOftowns) {
            if (dog.getTownLength() >= listTownLength) {

However if I add two towns to the list with town lengths of 2.5 and 5, then add user input 3, it shows the whole arrayList , since one of the pogs fulfill the condition (I suppose)



You can use filters for that case:
.filter(dog -> dog.tailLength >= listTailLength)

If not, you can always add an if condition inside of your existing for loop.