Reputation: 97
I have two arraylists of two types of objects. They are two types of users. I input an id(both types of users have unique integer ids), and want to find out if the user exists among the two arraylists.
ArrayList<Artist> artist = new ArrayList();
ArrayList<Customer> customer = new ArrayList();
class Artist implements User{
private String name;
private int a_id = 0;
private ArrayList<ArrayList> albums = new ArrayList();
private int money;
private int ma = 999;
private int mi = 100;
public Artist(String name) {
this.name = name;
a_id = (int)(Math.random()*((ma - mi) + 1)) + mi;
}
}
...<i>getters and setters</i>
class Customer implements User {
private String name;
private int subscription = 1;
private int due = 0;
private int c_id = 0;
private int ma = 9999;
private int mi = 1000;
public Customer(String name) {
this.name = name;
c_id = (int) (Math.random() * ((ma - mi) + 1)) + mi;
}
}
...<i>getters and setters</i>
Upvotes: 4
Views: 69
Reputation: 28279
Use anyMatch
method and ||
:
public boolean exist(ArrayList<Artist> artist, ArrayList<Customer> customer, int id) {
return artist.stream().anyMatch(user -> user.getA_id() == id) ||
customer.stream().anyMatch(user -> user.getC_id() == id);
}
Upvotes: 4
Reputation: 2369
You should think about having only one list of type User, because Artist and Customer are of type user (they both implement that interface).
Then you could simply use the stream api to determine wether a userId is there or not:
Optional<User> searchedUser = userList.stream().filter(User::getId.equals(userId).findFirst();
if(searchedUser.isPresent()) { //do something and handle missing }
Upvotes: 1