Arraylist check if CustomerID is in Rent ArrayList - java

I currently have 2 Arraylists which have Customer and Bike constructors data. I managed to enter both successfully to rent Arraylist using:
rent.add(new Rent(customers.get(1),bike.get(1)));
How do I check if CustomerID is already in Arraylist rent, and it will give error saying customer already renting?
public Rent(Customer customer, Bike bike) {
this.customers = customer;
this.bike = bike;
}
public Customer(int CustID, String CustFName, String CustLName) {
this.CustID = CustID;
this.CustFName = CustFName;
this.CustLName = CustLName;
}
public Bike(int BikeID, String BikeType, int PricePerDay,booleanisAvailable) {
this.BikeID = BikeID;
this.BikeType = BikeType;
this.PricePerDay = PricePerDay;
this.isAvailable = isAvailable;
}
protected ArrayList<Customer> customers = new ArrayList<Customer();
protected ArrayList<Bike> bike = new ArrayList<Bike>();
protected ArrayList<Rent> rent = new ArrayList<Rent>();

Assuming you are looking for a customer with a given custId, you can do this:
public boolean isAlreadyRenting(Customer cust) {
return rent.stream().anyMatch(r -> r.getCustomer().getCustId() == cust.getCustId());
}

If you override the equals method for your objects you can use contains on your ArrayList instances.

Related

Java8 stream: Iterate over nested list

Trying to get my head round the Java 8 streams syntax with a simple example. Had a look at the other similar questions on this topic, but could not find any solutions that would match my example and would work for me.
I have a class as follow
import java.util.List;
public class Car {
private String model;
private String make;
private String carName;
private List<Specification> specification;
public Car(String model, String make, String carName, List<Specification> specification) {
this.model = model;
this.make = make;
this.carName = carName;
this.specification = specification;
}
public String getModel() {
return model;
}
public String getMake() {
return make;
}
public String getCarName() {
return carName;
}
public List<Specification> getSpecification() {
return specification;
}
}
public class Specification {
private String name;
private String value;
public String getName() {
return name;
}
public String getValue() {
return value;
}
public Specification(String name, String value) {
this.name = name;
this.value = value;
}
}
And I have the main method
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class RegisterCar {
public static void main(String[] args) throws IOException {
List<String> carNames = new ArrayList<>();
carNames.add("Audi");
carNames.add("BMW");
carNames.add("Toyota");
List<String> colour = new ArrayList<>();
colour.add("red");
colour.add("white");
}
}
I want to create a list of car object with each item of carNames. But if the car name is 'Audi' or 'BMW' it should create only one object of the class as follow
List<Car> carList = new ArrayList<>();
Specification musicSystem = new Specification("MusicSysten" , "present");
List<Specification> specList= new ArrayList<>();
specList.add(musicSystem);
carList.add(new Car("Q5", "2020", "Audi", specList));
carList.add(new Car("X2", "2020", "BMW", specList));
But if the item is 'Toyota' then it should create two object each for each color.
List<Specification> specListRed= new ArrayList<>();
specListRed.add(musicSystem);
specListRed.add(redColor);
List<Specification> specListWhite= new ArrayList<>();
specListWhite.add(musicSystem);
specListWhite.add(whiteColor);
carList.add(new Car("Camry", "2020", "Toyota", specListRed));
carList.add(new Car("Camry", "2020", "Toyota", specListWhite));
I am trying to write a common method for creating object and adding to a list. I have tried something like this, but I won't create correct two object for Toyota.
carList = carNames.stream()
.map(carName -> new Car(model, make, carName, specList))
.collect(Collectors.toList());
please suggest how can I achieve this with streams.
If you want the name "Toyota" to be used twice it should be contained in the list of names twice, since the lambda in map() is executed for every name.
But inside your map-Call: Where do you get and model & make?
First thing you need to understand is that map operation always preserves same amount (i.e. cardinality) as your input.
If you will pass 3 items - no matter which function you have, result will always be 3.
Next thing worth looking into: flatMap function. This function can transform any amount of inputs to any amount of results! This looks like what we need.
var carList = carNames.stream()
.flatMap(carName -> {
if (carName.equals("Toyota") {
return Stream.of(new Car(model, make, carName, specList1),
new Car(model, make, carName, specList2));
} else {
return Stream.of(new Car(model, make, carName, specList));
})
.collect(Collectors.toList());
Since it's all about creation and holding of object. Foucus on equals() and and hashcode() methods.
#Override
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof Car)) {
return false;
}
Car car = (Car) o;
if (carName.equals("BMW")) {
return true;
}
if (carName.equals("Toyota")) {
return false;
}
return Objects.equals(carName , car.carName);
}
#Override
public int hashCode() {
return 1;
}
Driver methood
List<String> carNames = new ArrayList<>();
carNames.add("Audi");
carNames.add("BMW");
carNames.add("Toyota");
carNames.add("Toyota");
List<String> colours = new ArrayList<>();
colours.add("red");
colours.add("white");
Set carList = carNames.stream()
.map(carName -> {
Set ss = new HashSet();
if (carName.equals("Toyota")) {
ss.addAll(colours.stream().map(colr -> new Car("model" , "make" , carName , null)).collect(Collectors.toSet()));
} else {
ss.add(new Car("model" , "make" , carName , null));
}
return ss;
})
.collect(HashSet::new, Set::addAll, Set::addAll);

Process array list from map

We are trying to access the array of object that placed inside a map.
Can any one guide us to get length of the array as well as fetching each element from the list. Sample map object given bellow.
{
storeId = 1,
ShipToStreetLine1 = test 123,
ShipToCity = Seattle,
OrderDetails = [{
distributor_name = SS,
product_name = HORN 80897 AM GUN 300BO 125 HP 50/10
}]
}
We need to get the size of orderDetails array and if data present, then I want to fetch product_name.
You can try this:
Create a POJO which is type of what you are getting in orderDetails
Like
public class OrderDetailElement{
private String distributor_name;
private String product_name;
public String getDistributor_name() {
return distributor_name;
}
public void setDistributor_name(String distributor_name) {
this.distributor_name = distributor_name;
}
public String getProduct_name() {
return product_name;
}
public void setProduct_name(String product_name) {
this.product_name = product_name;
}
}
in your logic class you can do is
ArrayList<OrderDetailElement> orderDetails = yourMap.get("OrderDetails");
List<String> products = new ArrayList<String>();
if (orderDetails.size() > 0) {
for (OrderDetailElement orderDetailElement : orderDetails) {
products.add(orderDetailElement.getProduct_name());
}
}

Passing in a Class dynamically

Hopefully quite a simple question. How do I pass in a Class into an abstract method?
My abstract method is as follows:
public abstract class IDataList {
public LinkedList<IThing> getRows(IThing thing, String sql, List<Object> vals) throws Exception {
LinkedList<IThing> list = new LinkedList<>();
List<LinkedHashMap<String, Object>> rows = db.executeSelect(sql, vals);
for (HashMap<String, Object> row : rows) {
list.add(new thing(row));
}
rowCount = (long) getDb().executeScalar("SELECT FOUND_ROWS()");
return list;
}
}
Which is inherited by a concrete class:
public class DataList extends IDataList {
}
The IThing is currently an empty abstract class which is extended by an Thing, for example:
public class Thing extends IThing {
private long uid;
private String name;
public Thing(HashMap<String, Object> row) {
this.uid = (long) row.get("uid");
this.name = (String)row.get("name");
}
}
I want to be able to pass in Thing into a concrete class of IDataList, for example:
IDataList dataList = new DataList();
dataList.getRows(Thing, "select something", new ArrayList<>())
If you want to use Thing Class as a Row->Object mapper, it will be better to use org.springframework.jdbc.core.RowMapper
public class CustomerRowMapper implements RowMapper {
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
Customer customer = new Customer();
customer.setCustId(rs.getInt("CUST_ID"));
customer.setName(rs.getString("NAME"));
customer.setAge(rs.getInt("AGE"));
return customer;
}
}
public Customer findByCustomerId(int custId) {
String sql = "SELECT * FROM CUSTOMER WHERE CUST_ID = ?";
Customer customer = (Customer)getJdbcTemplate().queryForObject(sql, new Object[] { custId }, new CustomerRowMapper());
return customer;
}

Call length and specific items of list inside a list

Please view image for the scenario I want to describe.
I want to have a list inside a list and know what is the size of that list (inside) and how to call a particular data from that list.
--also please include how to add the hobbyList into candidateList
So let's say I want to call the size of hobbyList for the 2nd Candidate something like <code>CandidateList(1).HobbyList.length()</code>? or .size()?
What if I want to call the value of the 3rd hobby of the 2nd candidate
CandidateList(1).HobbyList(2)?
I don't know if I'm already clear with what I want so please don't hesitate to ask me.
Thank you! :)
Hobby Class
public class Hobby {
private int id;
private String hobby;
public Hobby(int id, String hobby) {
this.id = id;
this.hobby = hobby;
}
// Getters and setters
}
Candidate Class
import java.util.List;
public class Candidate {
private int id;
private String candidateName;
private List<Hobby> hobbies;
public Candidate(int id, String candidateName, List<Hobby> hobbies) {
this.id = id;
this.candidateName = candidateName;
this.hobbies = hobbies;
}
// Getters and setters
}
MainClassDemo having main method
import java.util.ArrayList;
import java.util.List;
public class MainClassDemo {
public static void main(String[] args) {
Hobby c1Hb1 = new Hobby(1, "Cricket");
Hobby c1Hb2 = new Hobby(2, "Hockey");
Hobby c1Hb3 = new Hobby(3, "Football");
List<Hobby> hobbies1 = new ArrayList<Hobby>();
hobbies1.add(c1Hb1);
hobbies1.add(c1Hb2);
hobbies1.add(c1Hb3);
Candidate candidate1 = new Candidate(1, "Ankit", hobbies1);
Hobby c2Hb1 = new Hobby(4, "FB");
Hobby c2Hb2 = new Hobby(5, "TW");
Hobby c2Hb3 = new Hobby(6, "INSTA");
Hobby c2Hb4 = new Hobby(6, "Pininterest");
Hobby c2Hb5 = new Hobby(6, "Quara");
List<Hobby> hobbies2 = new ArrayList<Hobby>();
hobbies2.add(c2Hb1);
hobbies2.add(c2Hb2);
hobbies2.add(c2Hb3);
hobbies2.add(c2Hb4);
hobbies2.add(c2Hb5);
Candidate candidate2 = new Candidate(2, "Bhumi", hobbies2);
List<Candidate> candidateList = new ArrayList<Candidate>();
candidateList.add(candidate1);
candidateList.add(candidate2);
System.out.println("No of Candidates:->" + candidateList.size());
System.out.println("Hobby list size for the 1st Candidate:->" + candidateList.get(0).getHobbies().size());
System.out.println("Hobby list size for the 2nd Candidate:->" + candidateList.get(1).getHobbies().size());
System.out.println("1st Hobby of 1st Candidate:->" + candidateList.get(0).getHobbies().get(0).getHobby());
System.out.println("3rd Hobby of 2nd Candidate:->" + candidateList.get(1).getHobbies().get(2).getHobby());
}
}
Output
No of Candidates:->2
Hobby list size for the 1st Candidate:->3
Hobby list size for the 2nd Candidate:->5
1st Hobby of 1st Candidate:->Cricket
3rd Hobby of 2nd Candidate:->INSTA
I'm not sure I understand your question fully.
Assuming you have a class Candidate and an class Hobby:
public class Candidate {
public final List<Hobby> hobbyList = new ArrayList<>();
...
}
public class Hobby {
...
}
And an list of candidates:
List<Candidate> candidateList;
You would get the number of hobbies of the second candidate in the list by calling with the expression:
candidateList.get(1).hobbyList.size()
and you would get the 3rd hobby in the hobby list of the 2nd candidate with:
candidateList.get(1).hobbyList.get(2)
to add a hobby to the second candidate, you would do:
candidateList.get(1).hobbyList.add(hobby);
Now I like to encapsulate the fields of a class, at least when they can be modified, so I would make hobbyList private, and add a few methods:
public class Candidate {
private final List<Hobby> hobbyList = new ArrayList<>();
public int getHobbyCount() {
return hobbyList.size();
}
public Hobby getHobby(int i) {
return hobbyList.get(i);
}
public List<Hobby> getHobbies() {
return new ArrayList<>(hobbyList);
}
public void addHobby(Hobby hobby) {
hobbyList.add(hobby);
}
public void removeHobby(Hobby hobby) {
hobbyList.remove(hobby);
}
public void removeAllHobbies() {
hobbyList.clear();
}
...
}
So you now can write things like:
candidateList.get(1).getHobbyCount();
candidateList.get(1).getHobby(2);
candidateList.get(1).add(hobby);
etc...

hibernate: insert instance with external "id class"

I'm using Hibernate + HSQL on JBOSS server, I need to saveOrUpdate() an Object which has an ID represented by another class:
public class RideId implements java.io.Serializable {
private int beginPop;
private int endPop;
private String requestUser;
public RideId() {
}
public RideId(int beginPop, int endPop, String requestUser) {
this.beginPop = beginPop;
this.endPop = endPop;
this.requestUser = requestUser;
}
...
so, "RideID" is the ID of the entity "Ride"
public class Ride implements java.io.Serializable {
private RideId id;
private User userByRequestUser;
private User userByAcceptUser;
private Pop pop;
private Boolean rideStatus;
public Ride() {
}
public Ride(RideId id, User userByRequestUser, Pop pop) {
this.id = id;
this.userByRequestUser = userByRequestUser;
this.pop = pop;
}
public Ride(RideId id, User userByRequestUser, User userByAcceptUser,
Pop pop, Boolean rideStatus) {
this.id = id;
this.userByRequestUser = userByRequestUser;
this.userByAcceptUser = userByAcceptUser;
this.pop = pop;
this.rideStatus = rideStatus;
}
...
how can I saveOrUpdate() a new Object of type Ride?
Thanks everyone and sorry for my english!
It's simple. You need to create first a new RideId, assign it to a new Ride and call saveOrUpdate with the Ride.
RideId id = new RideId(1, 2, "someuser");
Ride ride = new Ride(id, ...);
session.saveOrUpdate(ride);

Categories