How to search through arraylists for specific elements in java [duplicate]

I’m looking for the best solution here, I already have one that works, but I’m interested to see if there is a better one. Although the title may suggest otherwise, I am more than open to solutions that do not involve arraylists.

My question is essentially, is there a way to search through an array — with more than one element to each addition — for a specific string, int or bool.

Take the following code snippets;

...
    public KeplerLabFinal(String name, double mass, double semiMajorAxis){
        this.getPlanetName = name;
        this.getPlanetMass = mass;
        this.getSemiMajorAxis = semiMajorAxis;
    }
...

(inside main)

    public static void main(String[] args){
        ArrayList<KeplerLabFinal> planets = new ArrayList<>();
        planets.add(new KeplerLabFinal("Mercury", 3.285e23, 0.38710));
        planets.add(new KeplerLabFinal("Venus", 4.867e24, 0.72333));
        planets.add(new KeplerLabFinal("Earth", 5.972e24, 1));
        planets.add(new KeplerLabFinal("Mars", 6.39e23, 1.52366));
        planets.add(new KeplerLabFinal("Jupiter", 1.898e27, 5.20336));
        planets.add(new KeplerLabFinal("Saturn", 5.683e26, 9.53707));
        planets.add(new KeplerLabFinal("Uranus", 8.681e25, 19.1913));
        planets.add(new KeplerLabFinal("Neptune", 1.024e26, 30.0690));
        planets.add(new KeplerLabFinal("Pluto", 1.309e22, 39.4821));
...

Lets say, I wish to search for any planet with a semiMajorAxis between 2 and 15. I already figured out a solution, using a for loop to go through each entry, and then an if statement to look for which I want. Heres that code:

...
        for(KeplerLabFinal planet : planets){
            if(planet.getSemiMajorAxis >= 2 && planet.getSemiMajorAxis <= 15){
                System.out.println(planet.getPlanetName);
            }
        }
...

For less headache, here is a pastebin of the code combined.

As a last aside, if someone could please explain how/what the colon does in KeplerLabFinal planet : planets I would appreciate that. I originally used the for loop to print all the planets and their elements, but I got that from a different snippet that I repurposed for my own use. I found this, but It doesn’t exactly explain how it works, simply cases that its useful in.

  • 1

    Use a stream and filter the stream based on the property’s value being between two parameters.

    – 

  • 1

    Also, look up any tutorial on use of Java’s “for-each” loop.

    – 

  • Nope. For-loop it.

    – 




  • @Reilas: regarding, “As a last aside, if someone could please explain how/what the colon does in KeplerLabFinal planet : planets” — so “Nope” back at you. They’re looking for an explanation or tutorial on the “for-each loop” .

    – 




Leave a Comment