I have a list of
List<User> userList = ...
List<Long> UserIdWithBilling = .....
I search to set a field of User to true if the value in the list of UserIdWithBilling are found in the userList id field
for(Long userId : UserIdWithBilling){
Optional<User> optUserList = userList.stream()
.filter(ul->ul.getUserId().longValue()==userId)
.findFirst();
if(optUserList.isPresent()){
optUserList.get().setBilling(true);
}
}
that work but is there a way clean, faster
Maybe there is a way to do in via one line
Convert UserIdWithBilling to a set, then use contains in the filter.
Set<Long> ids = new HashSet<>(UserIdWithBilling);
userList.stream()
.filter(x -> ids.contains(x.getUserId()))
.forEach(x -> x.setBilling(true));
Here is the executable test with the old and new solution (as a one-liner)
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
#TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class UserList {
List<User> userList = new ArrayList<User>();
List<Long> userIdsWithBilling = new ArrayList<>();
#BeforeAll
public void setup() {
for (long id=1l; id<=10l; id++) userList.add(new User(id, false));
for (long id=1l; id<=5l; id++) userIdsWithBilling.add(id);
}
#Test
public void oldSolution() {
for (Long userId : userIdsWithBilling) {
Optional<User> optUserList = userList.stream()
.filter(ul -> ul.getId().longValue() == userId)
.findFirst();
if (optUserList.isPresent()) {
optUserList.get().setBilling(true);
}
}
for (int i=0; i<5; i++) assertTrue(userList.get(i).getBilling());
for (int i=5; i<10; i++) assertFalse(userList.get(i).getBilling());
}
#Test
public void newSolution() {
userList.stream().filter(user -> userIdsWithBilling.contains(user.getId()))
.forEach(user -> user.setBilling(true));
for (int i=0; i<5; i++) assertTrue(userList.get(i).getBilling());
for (int i=5; i<10; i++) assertFalse(userList.get(i).getBilling());
}
private static class User {
private Long id;
private Boolean billing = false;
public User(long id, boolean billing) {
this.id = id;
this.billing = billing;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public void setBilling(Boolean billing){
this.billing = billing;
}
public Boolean getBilling(){
return billing;
}
}
}
For large lists you can use parallel streams but please read the docs on that.
On one line, but keep in mind it changes the billing to true on the original userList. You have to rewrite if you want a new list like in your question.
UserIdWithBilling.forEach(
billedUser -> userList.stream().filter(u -> u.getUserId() == billedUser).toList()
.forEach(u -> u.setBilling(true)));
Related
an image of code for some reason
I am trying to have a little API run. Everything runs fine but I have to make an addition and am confused. I have to have it so in the URL when I type "localhost:8080/api/v1/{illness}" it will display the names of the people with that illness...help. I have included the two classes that I have. I didn't include my patient class. It's just the constructors and getters/setters for name, gender, illness, and id. I also didn't include the main well because its not needed
package com.sw409.Patientdemo.controller;
import java.util.List;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.sw409.Patientdemo.model.Patient;
import com.sw409.Patientdemo.service.PatientService;
#RestController
public class PatientController {
PatientService patService = new PatientService();
// CREATE
#PostMapping("api/v1/patients")
public Patient addPatient(#RequestBody Patient p) {
return patService.addPatient(p);
}
//GET ILLNESS (HELP!!!!!!!!!!!!!!!!!!!!!!!)
#PostMapping("api/v1/patients/{illness}")
public void patientIllness() {
return patService.patientIllness(name, illness)
}
// READ
#GetMapping("api/v1/patients")
public List<Patient> getPatient() {
return patService.getPatients();
}
// UPDATE
#PatchMapping("api/v1/patient/{patid}")
public void updatePatient(#PathVariable("patid") Integer id, #RequestBody Patient p) {
patService.updatePatient(id, p);
}
// DELETE
#DeleteMapping("api/v1/patient/{patid}")
public void deletePatient(#PathVariable("patid") Integer id) {
patService.deletePatient(id);
}
}
package com.sw409.Patientdemo.service;
import java.util.*;
import com.sw409.Patientdemo.model.Patient;
public class PatientService {
List<Patient> patientList = new ArrayList<>();
// Create
public Patient addPatient(Patient pat) {
patientList.add(pat);
return pat;
}
public List<Patient> getPatients() {
return patientList;
}
//(HELPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP)
public void patientIllness(String illness) {
for (int i = 0; i < patientList.size(); i++) {
if (patientList.get(i).equals(illness){
}
}
}
public void updatePatient(Integer id, Patient p) {
for (int i = 0; i < patientList.size(); i++) {
if (patientList.get(i).getId().equals(id)) {
patientList.set(i, p);
}
}
}
public void deletePatient(Integer id) {
for (int i = 0; i < patientList.size(); i++) {
if (patientList.get(i).getId().equals(id)) {
patientList.remove(i);
}
}
}
}
package com.sw409.Patientdemo.model;
public class Patient {
String name;
Integer id;
String gender;
String illness;
public Patient(String name, Integer id, String gender, String illness) {
super();
this.name = name;
this.id = id;
this.gender = gender;
this.illness = illness;
}
public Patient() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getIllness() {
return illness;
}
public void setIllness(String illness) {
this.illness = illness;
}
}
Controller
In case you want to get the value of something you should use GET instead of POST because POST use for creating or saving something
Your code:
#PostMapping("api/v1/patients/{illness}")
public void patientIllness() {
return patService.patientIllness(name, illness)
}
The parameter is missing patientIllness() that's why it cannot pass the value to service
The return type is void so you still cannot get anything
Suggestion:
#GetMapping("api/v1/patients/{illness}")
public List<Patient> patientIllness(#PathVariable String illness) {
return patService.patientIllness(illness);
}
Add paramiter in patientIllness(String illness) and you use it with path param so it will be patientIllness(#PathVariable String illness)
The return type should be something that you want to know if you want to know the List of Patients, return should be List<Patient>
Service
Your code:
public void patientIllness(String illness) {
for (int i = 0; i < patientList.size(); i++) {
if (patientList.get(i).equals(illness){
}
}
}
The return type is void so you have change it if you want to return something to controller
It's worng in this code patientList.get(i).equals(illness) Type of patientList.get(i) is Patient and you compare it with String
Suggestion1:
public List<Patient> patientIllness(String illness) {
List<Patient> result = new ArrayList<>();
for (int i = 0; i < patientList.size(); i++) {
if (patientList.get(i).getIllness().equals(illness)) {
result.add(patientList.get(i));
}
}
return result;
}
The return type will be List<Patient>
You should compare with the same type patientList.get(i).getIllness().equals(illness)
Suggestion2: you can change to for each
public List<Patient> patientIllness(String illness) {
List<Patient> result = new ArrayList<>();
for (Patient patient : patientList) {
if (patient.getIllness().equals(illness)) {
result.add(patient);
}
}
return result;
}
Suggestion3: You can change it to use steam, filter, and collect it to list
public List<Patient> patientIllness(String illness) {
return patientList.stream()
.filter(patient -> patient.getIllness().equals(illness))
.collect(Collectors.toList());
}
First of all you need to change your controller function to something like this:
#PostMapping("api/v1/patients/{illness}")
public List<Patient> patientIllness(#PathVariable String illness) {
return patService.patientIllness(illness)
}
I don't understand why you called your service function with two arguments, because it can accept only one. You also need to make this function return list of patients instead of void. And illness is just a path variable, you use it in different functions, so you should understand it. And in your patient service you just need to use filter function, so it will look similiar to this:
public List<Patient> patientIllness(String illness) {
return patientList.stream().filter(patient->patient.getIllness().equals(illness)).collect(Collectors.toList());
}
patientIllness in Controller needs a parameter illness to accept illness path variable from URL.
Also name variable is not initialised (which is provided to service layer, but not used in service layer). So the name parameter can be removed.
Request mapping should be GET to retrieve data - recommended.
patientIllness in Controller should return a List<Patient> as received from service layer.
I'm pretty new to java, trying write some unit test for my code. But stuck on one of them.
this is method i want test :
public Reservation findSpecificReservation(Long id) throws NullPointerException{
Reservation reservation = null;
Optional<Reservation> byId = iReservationRepository.findById(id);
if(byId.isPresent()){
reservation = byId.get();
}
return reservation;
}
those are variables mock and setup :
private IReservationService iReservationService;
#Mock
private IReservationRepository repository;
#Before
public void setUp() {
initMocks(this);
iReservationService = new ReservationServices(repository);
}
and test looks like :
#Test
public void shouldFindReservation() {
Long id = 1L;
Reservation expected = getDefaultReservation();
when(iReservationService.findSpecificReservation(id)).thenReturn(getDefaultReservation());
Reservation actual = iReservationService.findSpecificReservation(id);
Assert.assertThat(expected, is(actual));
}
My test throws nullpointer exception in the lane where im trying do when thenReturn, ireservationService.findSpecificReservatin(id) throws it.
Can someone please let me know what im doing wrong ?
Im begginer in programming and will be glad if you can go soft on me Thanks !
edit adding whole classes :
package com.hotelReservation.hotelReservation.services;
import com.hotelReservation.hotelReservation.domain.ReservationStatusResponse;
import com.hotelReservation.hotelReservation.entity.Reservation;
import com.hotelReservation.hotelReservation.entity.User;
import com.hotelReservation.hotelReservation.repository.IReservationRepository;
import com.hotelReservation.hotelReservation.repository.IRoomRepository;
import com.hotelReservation.hotelReservation.repository.IUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
#Service
public class ReservationServices implements IReservationService {
private IReservationRepository iReservationRepository;
private IRoomRepository iRoomRepository;
private IUserRepository iUserRepository;
#Autowired
public ReservationServices(IReservationRepository iReservationRepository) {
this.iReservationRepository = iReservationRepository;
this.iRoomRepository = iRoomRepository;
this.iUserRepository = iUserRepository;
}
#Override
public ReservationStatusResponse addReservation(LocalDate begin, LocalDate end, Long roomId, Long userId, String breakfast, String diner, String rentCar, int adultsForReservation) {
PriceCounter priceCounter = new PriceCounter();
int days = 0;
if (end.isAfter(begin)) {
days = begin.until(end).getDays();
}
int price = priceCounter.calculatePrice(breakfast, diner, rentCar, days, adultsForReservation);
Reservation newReservation = Reservation.builder()
.begin(begin)
.end(end)
.roomForReservation(iRoomRepository.findById(roomId).get())
.user(iUserRepository.findById(userId).get())
.breakfast(breakfast)
.dinner(diner)
.rentCar(rentCar)
.adultsForReservation(adultsForReservation)
.price(price)
.build();
ReservationStatusResponse reservationStatusResponse = checkIsReservationDatesAreNotTaken(newReservation.getRoomForReservation()
.getId(), newReservation.getBegin(), newReservation.getEnd());
if (reservationStatusResponse.isPossible()) {
iReservationRepository.save(newReservation);
}
return reservationStatusResponse;
}
#Override
public void cancelReservation(Long id) {
iReservationRepository.deleteById(id);
}
public List<Reservation> findAllReservationOfSpecificUser(Long id) {
List<Reservation> allByUserId = iReservationRepository.findAllByUserId(id);
return new ArrayList<>(allByUserId);
}
public Reservation findSpecificReservation(Long id) throws NullPointerException {
Reservation reservation = null;
Optional<Reservation> byId = iReservationRepository.findById(id);
if (byId.isPresent()) {
reservation = byId.get();
}
return reservation;
}
public List<Reservation> findAllReservationsOnRoom(Long roomId) {
return iReservationRepository.findReservationsByRoom(roomId);
}
#Override
public ReservationStatusResponse checkIsReservationDatesAreNotTaken(Long roomId, LocalDate begin, LocalDate end) {
ReservationStatusResponse reservationStatusResponse = new ReservationStatusResponse();
if (begin.isAfter(end) || begin.isBefore(LocalDate.now())) {
reservationStatusResponse.setPossible(false);
reservationStatusResponse.setReason("Begin date is after end date or before today !");
return reservationStatusResponse;
}
int newReservationPeriod = begin.until(end).getDays();
List<LocalDate> newReservationDates = new ArrayList<>();
List<LocalDate> takenReservationDates = new ArrayList<>();
for (int i = 0; i <= newReservationPeriod; i++) {
newReservationDates.add(begin.plusDays(i));
}
List<Reservation> allReservationsOnRoom = findAllReservationsOnRoom(roomId);
for (Reservation r :
allReservationsOnRoom) {
int existingReservationPeriod = r.getBegin().until(r.getEnd()).getDays();
for (int i = 0; i <= existingReservationPeriod; i++) {
takenReservationDates.add(r.getBegin().plusDays(i));
}
for (LocalDate l :
takenReservationDates) {
for (LocalDate lo :
newReservationDates) {
if (l.isEqual(lo)) {
reservationStatusResponse.setReason("Date is taken");
reservationStatusResponse.setPossible(false);
return reservationStatusResponse;
}
}
}
}
reservationStatusResponse.setPossible(true);
reservationStatusResponse.setReason("Possible");
return reservationStatusResponse;
}
#Override
public List<Reservation> findAll() {
return iReservationRepository.findAll();
}
}
test class :
package com.hotelReservation.hotelReservation.services;
import com.hotelReservation.hotelReservation.domain.ReservationStatusResponse;
import com.hotelReservation.hotelReservation.entity.Reservation;
import com.hotelReservation.hotelReservation.entity.Room;
import com.hotelReservation.hotelReservation.repository.IReservationRepository;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;
import static org.hamcrest.CoreMatchers.is;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
public class ReservationServicesTest {
private IReservationService iReservationService;
#Mock
private IReservationRepository repository;
#Before
public void setUp() {
initMocks(this);
iReservationService = new ReservationServices(repository);
}
#Test
public void ShouldDeleteReservationById() {
Long id = 12L;
Mockito.doNothing().when(repository).deleteById(id);
iReservationService.cancelReservation(id);
Mockito.verify(repository, Mockito.times(1)).deleteById(id);
}
#Test
public void shouldFindReservation() {
Long id = 1L;
Reservation expected = getDefaultReservation();
when(iReservationService.findSpecificReservation(id)).thenReturn(getDefaultReservation());
Reservation actual = iReservationService.findSpecificReservation(id);
Assert.assertThat(expected, is(actual));
}
#Test(expected = NullPointerException.class)
public void shouldThrowNullPointerExceptionOnFindingReservationWithDoesntExist() {
Long id = 1L;
iReservationService.findSpecificReservation(id);
}
#Test
public void shouldReturnListOfReservations() {
Long id = 1L;
List<Reservation> reservationListFromDb = getReservationDatesListFromDb();
when(iReservationService.findAllReservationsOnRoom(id)).thenReturn(reservationListFromDb);
List<Reservation> actual = iReservationService.findAllReservationsOnRoom(id);
Assert.assertArrayEquals(reservationListFromDb.toArray(), actual.toArray());
}
private List<Reservation> getReservationDatesListFromDb() {
Reservation first = Reservation.builder()
.begin(LocalDate.of(2018, 05, 01))
.end(LocalDate.of(2018, 05, 03))
.build();
Reservation second = Reservation.builder()
.begin(LocalDate.of(2017, 05, 01))
.end(LocalDate.of(2017, 05, 03))
.build();
return Arrays.asList(first, second);
}
private Reservation getDefaultReservation() {
return Reservation.builder()
.begin(LocalDate.of(2018, 7, 23))
.end(LocalDate.of(2018, 7, 29))
.reservationId(1234L)
.roomForReservation(getDefaultRoom())
.rentCar("NO")
.breakfast("NO")
.dinner("NO")
.adultsForReservation(2)
.build();
}
public Room getDefaultRoom() {
return Room.builder()
.howManyPeople(2)
.id(12L)
.roomClass("Hobbit")
.build();
}
}
You forgot the #InjectMocks over iReservationService.
#InjectMocks
private IReservationService iReservationService;
Also there's no need for doing
iReservationService = new ReservationServices(repository);
in your setup() method.
And you should be mocking the calls of repository and not the iReservationService itself.
I am new to java and reporting tool BIRT, I am trying to create a simple report using Pojo in Birt but I can't get it to work I create my java classes in other project and generate a jar file after that I use it to create a data source but when I try to create a data set it doesnt work, I couldn't select classes to proceed
package com.test.pojoproject;
import java.io.Serializable;
public class Person implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private int id;
private String name;
private String address;
public Person(){
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setAddress(String address) {
this.address = address;
}
}
package com.test.pojoproject;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class Main implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private static List<Person> list = new ArrayList<Person>();
public static void main(String[] args) {
Main.generateData();
Main.getList();
// display created list
//list.forEach(person -> System.out.println(person.getName()));
}
public static void generateData(){
List<Person> list = new ArrayList<Person>();
for (int i = 0; i < 30; i++) {
Person person = new Person();
person.setId(i+1);
person.setName("person " + (i+1));
person.setAddress("address " + (i+1));
list.add(person);
}
Main.list = list;
}
public static List<Person> getList(){
return Main.list;
}
}
I found a solution BIRT needs to use a class withe methodes open, next and close I will post my dataset class below
package com.test.pojoproject;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class PersonDataSet {
public Iterator<Person> itr;
public List<Person> getPersons() {
List<Person> persons = new ArrayList<Person>();
for (int i = 0; i < 30; i++) {
Person person = new Person();
person.setId(i+1);
person.setName("person " + (i+1));
person.setAddress("address " + (i+1));
persons.add(person);
}
return persons;
}
public void open(Object obj, Map<String,Object> map) {
}
public Object next() {
if (itr == null)
itr = getPersons().iterator();
if (itr.hasNext())
return itr.next();
return null;
}
public void close() {
}
}
Created 2 task which insert values inside list .
Then execute those task using executor service .
And at last try to find out the values inside those list .
Why values are not inserted into list once executor service is shutdown ?
Not able to find out the reason behind this behavior , can any one explain this .
package com.executors;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;
public class ExecutorTesting {
public static AtomicInteger counter = new AtomicInteger(0);
static List<employee> list = new ArrayList<employee>();
public static void main(String[] args) throws InterruptedException, ExecutionException {
list = Collections.synchronizedList(list);
Callable<List<employee>> c1 = new Callable<List<employee>>() {
#Override
public List<employee> call() throws Exception {
for (int i = 0; i < 10; i++) {
list.add(new employee("varun", ExecutorTesting.counter.incrementAndGet()));
}
return list;
}
};
Callable<List<employee>> c2 = new Callable<List<employee>>() {
#Override
public List<employee> call() throws Exception {
for (int i = 0; i < 10; i++) {
list.add(new employee("varun", ExecutorTesting.counter.incrementAndGet()));
}
return list;
}
};
ExecutorService es = Executors.newFixedThreadPool(2);
try {
Future<List<employee>> ef1 = es.submit(c1);
Future<List<employee>> ef2 = es.submit(c2);
if (ef1.isDone()) {
System.out.println("first value : " + ef1.get());
}
if (ef2.isDone()) {
System.out.println("first value : " + ef2.get());
}
System.out.println(list);
} finally {
es.shutdown();
}
}
}
class employee {
String name;
int id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public employee(String name, int id) {
super();
this.name = name;
this.id = id;
}
public String toString() {
return this.name + " : " + this.id;
}
}
You're calling future.isDone() immediately after submitting it to the ExecuterService. In most cases the execution will not have been started, let alone be finished. So both isDone calls return false and you just finish the whole thing.
I'm not sure about the concrete scenario you're facing, but to solve the problem in this particular test code, you just need to call get on each Future:
System.out.println("first value : " + ef1.get(10, TimeUnit.SECONDS));
System.out.println("first value : " + ef2.get(10, TimeUnit.SECONDS));
I left your copy&paste-error of your output-text ;-)
I have two classes:
Products:
01; Desinfectante
02; Aerosol
03; Limpia Vidrio
04; Desengrasante
05; Mata mosquitos
06; Mata cucarachas
07; Aceite en aerosol
Instructions:
01;1;Elevar la masa hasta llegar a tal punto;0;10
01;1;Mezclar este material con anterior;1;15
01;2;Relevar;2;5
01;3;Llevar;00;0
02;1;Descripcion;7;2
02;2;Descripcion;6;2
02;2;Descripcion;00;0
03;1;Descripcion;1;1
03;1;Descripcion;2;9
03;2;Descripcion;00;0
03;3;Descripcion;5;2
03;4;Descripcion;6;2
03;4;Descripcion;3;10
04;1;Descripcion;00;0
04;2;Descripcion;1;2
04;3;Descripcion;1;0
04;3;Descripcion;2;2
04;3;Descripcion;3;2
04;4;Descripcion;7;1
04;4;Descripcion;6;2
05;1;Descripcion;7;20
05;1;Descripcion;6;9
05;2;Descripcion;00;0
05;3;Descripcion;1;2
05;3;Descripcion;2;10
06;1;Descripcion;2;12
06;1;Descripcion;4;1
06;1;Descripcion;6;8
06;2;Descripcion;5;4
06;2;Descripcion;7;2
07;1;Descripcion;1;12
07;1;Descripcion;2;2
07;2;Descripcion;3;19
07;2;Descripcion;4;4
07;2;Descripcion;00;2
07;2;Descripcion;5;12
The thing is this: i have to insert the instructions ArrayList into the Products. The link between them is the first number, that is the code of the product.
I tried two things, the first one:
public static ArrayList<Productos> InsertInstInProd(ArrayList<Instrucciones> instructions, ArrayList<Productos> products)
{
for (int i = 0; i < products.size()-1; i++)
{
int n = 0;
for (int j = 0; j < instructions.size()-1; j++)
{
int first = products.get(i).getNumero();
int second = instructions.get(j).getCodProd();
if (first == second)
{
products.get(i).getInstr().get(n).setCodIns(instructions.get(j).getCodIns());
products.get(i).getInstr().get(n).setCodProd(instructions.get(j).getCodProd());
products.get(i).getInstr().get(n).setDescr(instructions.get(j).getDescr());
products.get(i).getInstr().get(n).setMat(instructions.get(j).getMat());
products.get(i).getInstr().get(n).setMatNec(instructions.get(j).getMatNec());
n++;
}
}
n = 0;
}
The second one:
public static ArrayList<Productos> InsertInstInProd(ArrayList<Instrucciones> instructions, ArrayList<Productos> products)
{
for (int i = 0; i < products.size()-1; i++)
{
int n = 0;
for (int j = 0; j < instructions.size()-1; j++)
{
int first = products.get(i).getNumero();
int second = instructions.get(j).getCodProd();
if (first == second)
{
products.get(i).setInstr(instructions);
n++;
}
}
n = 0;
}
return products;
}
You are getting NullPointerException because of
products.get(i).getInstr().get(n).setCodIns(instructions.get(j).getCodIns());
You are not checking whether the list products.get(i).getInstr() has elements or not. When the list is empty and when you are accessing it as products.get(i).getInstr().get(0) it's throwing you NullPointerException because trying to get the first element of an empty list. So before you do this operation, make sure that products.get(i).getInstr() is not empty.
If they are of same type, you can directly add the whole arraylist :
products.get(i).getInstr().addAll(instructions); // again make sure that is not empty.
If you just want to replac, use :
products.get(i).setInstr(instructions.get(j));
Products Class
package productsandinstructions;
import java.util.List;
public class Product {
private int productId;
private String productName;
private List instructions;
public int getProductId() {
return productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public List getInstructions() {
return instructions;
}
public void setInstructions(List instructions) {
this.instructions = instructions;
}
}
Instruction Class
package productsandinstructions;
public class Instruction {
private int productId;
private int instructionId;
private String instDesc;
private int mat;
private int matNec;
private boolean done;
public int getProductId() {
return productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public int getInstructionId() {
return instructionId;
}
public void setInstructionId(int instructionId) {
this.instructionId = instructionId;
}
public String getInstDesc() {
return instDesc;
}
public void setInstDesc(String instDesc) {
this.instDesc = instDesc;
}
public int getMat() {
return mat;
}
public void setMat(int mat) {
this.mat = mat;
}
public int getMatNec() {
return matNec;
}
public void setMatNec(int matNec) {
this.matNec = matNec;
}
public boolean isDone() {
return done;
}
public void setDone(boolean done) {
this.done = done;
}
}
Main Class
package productsandinstructions;
import java.util.List;
public class ProductsAndInstructionsMain {
private List products;
private List instructions;
public List getProducts() {
return products;
}
public void setProducts(List products) {
this.products = products;
}
public List getInstructions() {
return instructions;
}
public void setInstructions(List instructions) {
this.instructions = instructions;
}
public static void main(String[] args) {
ProductsAndInstructionsMain main = new ProductsAndInstructionsMain();
main.mergeProductsAndInstructions();
}
public void mergeProductsAndInstructions() {
for (Product product : products) {
for (Instruction instruction : instructions) {
if ((!(instruction.isDone())) && (instruction.getProductId() == product.getProductId())) {
product.getInstructions().add(instruction);
instruction.setDone(true);
}
}
}
}
}