PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, November 5, 2022

[FIXED] How to check whether an object exists a List using Streams

 November 05, 2022     arraylist, java, java-stream, lambda     No comments   

Issue

I have to create a result list by adding objects.

Here is my code.

private ArrayList<Car> carsInStore ;

public boolean addCarToStore(String type, String model, String color,
                                    int maxSpeed,int year,String plateNumber) {
    for (Car car : carsInStore) {
        if (car.getPlateNumber()==plateNumber) {
            return false;
        }
        else {
            carsInStore.add(new Car(type, model, color, maxSpeed,
                                        year, plateNumber));
            return true;
        }
    }
}

I need to check if a car with the given plateNumber already exist within the ArrayList, if it exists, then a new car will not be added.

I'd like to perform the check via Java streams.

I'm using Java 11.


Solution

If you want to rewrite your method using stream, as suggested in the comments, you could check with a stream if a Car with the given plate number already exists within the List; if it does not, then you could add it to carsInStore.

Also, to check whether two String are equal you need to use the equals method. The == operator checks the content of the confronted variables, in case of references their content corresponds to the memory address of the object they point, not the actual value they represent.

private ArrayList<Car> carsInStore;

public boolean addCarToStore(String type, String model, String color, int maxSpeed, int year, String plateNumber) {
    if (carsInStore.stream()
        .filter(c -> c.getPlateNumber().equals(plateNumber))
        .findFirst()
        .isEmpty()) {
        return false;
    }

    carsInStore.add(new Car(type, model, color, maxSpeed, year, plateNumber));
    return true;
}


Answered By - Dan
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing