How to set for loop array values to a bean - java

I have the following loop in a controller class:
for (int i = 0; i <= locationArr.length - 1; i++) {
data.put(idArr[i], locationArr[i]);
locationBean.setLocation_name(locationArr[i]);
}
My Bean looks like :
public class LocationBean {
private String region_id;
private String region_name;
private String location_id;
private String location_name;
//getters and setters
}
I am trying to set location_name as setLocation_name(locationArr[i]);
But only getting last values of the loop [i] is being assigned.

If you like to have multiple location names you can do that by e.g. a List or more general any Collection if order does not matter.
Here an example:
public class LocationBean {
private String region_id;
private String region_name;
private String location_id;
private List<String> locationNames = new ArrayList<>();
//getters and setters
public List<String> getLocationNames() {
return locationNames;
}
}
usage in your loop:
locationBean.getLocationNames().add(locationArr[i]);
I did not refactor all your example code to be complient to the java naming convention. You should name your variables in camel case.

Either u can create a list of LocationBean objects :
ArrayList <LocationBean> locationBeanList = new ArrayList <LocationBean>)();
for (int i = 0; i <= locationArr.length - 1; i++) {
data.put(idArr[i], locationArr[i]);
locationBean = new LocationBean();
locationBean.setLocation_name(locationArr[i]);
locationBeanList.add(locationBean);
}
Or, u can create list of locations in single location bean
public class LocationBean {
private String region_id;
private String region_name;
private String location_id;
private List<String> location_name_list = new ArrayList<String>();
//getters and setters
}
List<String> locationList = new ArrayList <String>();
for (int i = 0; i <= locationArr.length - 1; i++) {
data.put(idArr[i], locationArr[i]);
locationList.add(locationArr[i]);
}
locationBean.setLocation_name_list(locationList );

LocationBean with a List
You want to store every location name, not set ONE value. So you want a method addLocationName store it into a Collection
locationBean.addLocationName(locationArr[i]);
That method is simple, it will add every String into a List<String>
private List<String> locationsName;
private List<String> locationsId;
public LocationBean (){
locationsName = new ArrayList<String>();
locationsId= new ArrayList<String>();
}
public boolean addLocationName(string locationName){
return this.locationsName.add(locationName);
}
public boolean addLocationId(string locationId){
return this.locationsId.add(locationId);
}
Of course, you would need to do the same with location_id, so a Bean would be smarter :
public class Location{
private String id;
private String name;
public Location(String id, String name){ ... }
//constructor and getter
}
and simply use a List<Location> instead. That way, both id and name are stored together.
public boolean addLocation(Location location){
return this.locations.add(location);
}
or passing the values
public boolean addLocation(String id, String name){
return this.locations.add(new Location(id, name));
}
List of LocationBean
Or your bean should only have one location and then this is in your loop that you need to store every instance of LocationBean into a List<LocationBean> (don't forget to create a new instance each time`
List<LocationBean> locations = new ArrayList<>();
for (int i = 0; i <= locationArr.length - 1; i++) {
locationBean = new LocationBean(); //new instance each time
locationBean.setLocation_name(locationArr[i]);
locations.add(locationBean); //add into the list
}

Related

Joining 2 Arraylists JAVA

So I have this class which reads from 2 files and fills 2 Arraylists
with Contact Objects. Now I want to Merge these Arraylists to a new
Arraylist which then I want to Sort and eliminate duplicates. My
problem is: How do I get the filled Arraylists to another method so I
can do the sorting?
Here is my Code:
import java.util.List;
import java.util.Scanner;
final class Addressbook{
public List<Contact> contacts1 = new ArrayList<Contact>();
public List<Contact> contacts2= new ArrayList<Contact>();
public List<Contact> allcontacts = new ArrayList<Contact>();
public void readContacts1(Scanner scanner1) {
scanner1.useDelimiter(";");
while (scanner1.hasNext()) {
final Contact contact= readContacts1(scanner1);
contacts1.add(Contact);
}
}
public void readContacts2(Scanner scanner2) {
while (scanner2.hasNext()) {
final Contact contact = readContacts2(scanner2);
contacts.add(contact);
}
}
public int ContactSearch1(Contact c) {
for (int i = 0; i < contacts1.size(); i++)
if (contacts1.get(i).equals(c))
return i;
return -1;
}
public int ContactSearch2(Contact c) {
for (int i = 0; i < contacts2.size(); i++)
if (contacts2.get(i).equals(c))
return i;
return -1;
}
private static Contact readContact1(Scanner scanner1) {
scanner1.useDelimiter(";");
final String name= scanner1.next();
final String lastname = scanner1.next();
final String address = scanner1.next();
final String number = scanner1.next();
final Contact contact= new Contact(name, lastname, address, number);
return contact;
}
private static Contact ReadContact2(Scanner scanner2) {
scanner2.useDelimiter(";");
final String name= scanner2.next();
final String lastname = scanner2.next();
final String address = scanner2.next();
final String number = scanner2.next();
final Contact contact= new Contact(name, lastname, address, number);
return contact;
}
}
First, the provided code contains a lot of duplicated parts which may easily be encapsulated in a separate helper class which takes care of reading and searching the lists.
final class Addressbook{
private List<Contact> contacts1;
private List<Contact> contacts2;
private List<Contact> allContacts;
private static class ContactHelper {
public static List<Contact> readContacts(Scanner scanner) {
// scanner.setDelimiter(";"); // it's better to set this parameter in the call
List<Contact> result = new ArrayList<>();
boolean hasData = scanner.hasNext();
while (hasData) {
final String name= scanner.next();
final String lastname = (hasData &= scanner.hasNext()) ? scanner.next() : "NO_LAST_NAME";
final String address = (hasData &= scanner.hasNext()) ? scanner.next() : "NO_ADDRESS";
final String number = (hasData &= scanner.hasNext()) ? scanner.next() : "NO_NUMBER";
result.add(new Contact(name, lastname, address, number));
hasData = scanner.hasNext();
}
return result;
}
public static int indexOfContact(Contact contact, List<Contact> list) {
Objects.requireNonNull(contact);
Objects.requireNonNull(list);
for (int i = 0, n = list.size(); i < n; i++) {
if (contact.equals(list.get(i))) {
return i;
}
}
return -1;
}
}
}
Then appropriate methods to set fields contacts1, contacts2 should use the helper's methods:
// class AddressBook
public void readContacts1(Scanner scanner) {
contacts1 = ContactHelper.readContacts(scanner);
}
public void readContacts2(Scanner scanner) {
contacts2 = ContactHelper.readContacts(scanner);
}
A method to join the lists, sort them, and remove the duplicates can be implemented using TreeSet if class Contact implements interface Comparable required for sorting the contacts in their natural order, otherwise custom comparator must be provided.
// another helper method
public static List<Contact> joinContacts(List<Contact> ... contactLists) {
Set<Contact> sortedWithoutDups = new TreeSet<>();
for (List<Contact> list : contactLists) {
if (null != list) {
sortedWithoutDups.addAll(list);
}
}
return new ArrayList<>(sortedWithoutDups);
}
// setting allContacts
public void joinContacts() {
allContacts = AddressBook.joinContacts(contacts1, contacts2);
}
This task can be resolved using Stream API (allowing for joining more than 2 lists any of which may be null):
// AddressBook
public void joinContacts() {
allContacts = ContactHelper.joinContactLists(contacts1, contacts2);
}
// ContactHelper
public static List<Contact> joinContactLists(List<Contact> ... lists) {
return Arrays.stream(lists) // Stream<List<Contact>>
.filter(Objects::nonNull) // filter out null lists
.flatMap(List::stream) // convert to Stream<Contact>
.sorted() // sort
.distinct() // _and then_ remove duplicates
.collect(Collectors.toList());
}
contacts1.addAll(contacts2);
contacts1.sort((o1, o2) -> o1 < o2 ? o1 : o2);
contacts1.addAll(contacts2)
This adds all contacts2 to contacts1 and contacts1 List will have all the contacts.
Here u can replace o1 < o2 can be replaced with the logic u need to sort.
The easiest way to ensure, that you do not have duplicates in your ArrayList is to copy your list into a Collection that does not allow duplicates (for example a set) and then copy it back into the ArrayList you need. I would recommend to check out this post for this:
Answers to Question: I have an ArrayList, and I want to remove repeated strings from it. How can I do this?
Ultimately your problem could be answered the following way (using the code of mentioned blog post):
allcontacts.addAll(contacts1);
allcontacts.addAll(contacts2);
Set<Contact> set = new HashSet<>(allcontacts);
allcontacts.clear();
allcontacts.addAll(set);
Now you got rid of all duplicates and merged the ArrayLists contacts1 and contacts2 into allcontacts.
You now only have to sort allcontacts, which can be done like this (if Contact implements Comparable):
Collections.sort(allcontacts);

Deep copy Object ArrayList in Java

Java object to copy:
public class InfoDtcEx implements Serializable {
private static final long serialVersionUID = 1L;
private String infoCall="";
private String infoNotCall="";
private String infoTarget="";
private String infoTotal="";
private String infoValue="";
private ArrayList<String> valueList;
public InfoDtcEx(String infoCall, String infoNotCall,
String infoTarget, String infoTotal, String infoValue) {
this.infoCall = infoCall;
this.infoNotCall = infoNotCall;
this.infoTarget = infoTarget;
this.infoTotal = infoTotal;
this.infoValue = infoValue;
this.infoValueBefore = this.infoValue;
}
public InfoDtcEx(InfoDtc infoDtc) {
this.infoCall = infoDtc.getinfoDtcCall();
this.infoNotCall = infoDtc.getinfoDtcNotCall();
this.infoTotal = infoDtc.getinfoDtcTotal();
this.infoValue = infoDtc.getinfoDtcValue();
this.infoValueBefore = this.infoValue;
}
//getters and setters
}
I tried Using below method to deep copy as suggested at How to copy elements from an ArrayList to another one NOT by reference?:
private ArrayList<InfoDtcEx> copyInfoList(ArrayList<InfoDtcEx> infoListExChanged) {
infoListExChanged.clear();
for (int i = 0; i < infoListEx.size(); i++) {
String infoCall = infoListEx.get(i).getinfoCall();
if(infoCall != "Yes") {
infoListExChanged.add(infoListEx.get(i));
}
}
return infoListExChanged;
}
But, this is changing the actual list infoListEx as well.
You are not performing the deep copy as suggested in the post you linked to.
That post had the following line in the accepted answer :
copia.add(new Articulo_Venta(av.get(i)));
Notice the construction of the new Articulo_Venta. Your code is not calling new.
So try changing your line where you are adding to the list to create a new object, so :
infoListExChanged.add(new InfoDtcEx(infoListEx.get(i)));

Looping for array lists and adding values which match two array lists into a new one

I'm trying to make a program that matches a clients interests with aspects of a holiday, I have an array list of holidays and an array list of strings for the clients interests and I wanted to create a new array list which would add all elements that are contained in both. This is what I have but it comes up with a null pointer exception, Any ideas where I've gone wrong?
the debugger points towards the disjoint and at " int c1size = c1.size();"
Relevant parts of code...
In main...
ClientExt1 marina = new ClientExt1("Marina",14321,"marina.calder1#btinternet.com");
ArrayList<String> interests = new ArrayList<>();
interests.add("History");
interests.add("Music");
marina.setInterests(interests);
holidaySeller.getHolidayMatches(marina);
Client...
public class ClientExt1 {
private String name;
private int id;
private String email;
private HolidayExt1 holidayBooked;
private ArrayList<String> interests;
public ClientExt1(String name, int id, String email){
this.name=name;
this.id=id;
this.email=email;
}
public void setInterests(ArrayList interests) {
this.interests=interests;
}
public ArrayList<String> getInterests(){
return interests;
Company class...
public class CompanyExt1 {
protected ArrayList<StaffExt1> staffMembers;
protected ArrayList<HolidayExt1> holidays;
protected ArrayList<GuideExt1> holidayGuides;
protected ArrayList<AdventureExt1> adventureHolidays;
protected ArrayList<CultureExt1> cultureHolidays;
private ArrayList<String> matchedHolidays;
public ArrayList<String> findHolidayMatch(ClientExt1 client) {
ArrayList interests = client.getInterests();
int i;
for (i = 0; i < holidays.size() && i< interests.size(); i++) {
if (!Collections.disjoint(holidays.get(i).getAspects(), interests)) {
matchedHolidays.add(holidays.get(i).getName());
}
}
return matchedHolidays;
}
public void getHolidayMatches(ClientExt1 client){
System.out.println(client.getName() + ", the holidays recommended to you based on your interests from this company are:" + findHolidayMatch(client));
}
}
You need to initialize holidays before you use it and matchedHolidays before you add values to it in findHolidayMatch
I would actually make matchedHolidays a local variable instead of a class member since it is only used in the scope of the findHolidayMatch method.

Java sort ArrayList in alphabetical order and doing the same changes on other arrays

I have four ArrayLists. I want to sort one of them alphabetically with case ignored and do the same changes in the other three ArrayLists.
ArrayList<String> arrPackage = new ArrayList<>();
ArrayList<String> arrPackageDates = new ArrayList<>();
ArrayList<String> arrPackageDuration = new ArrayList<>();
ArrayList<String> arrPackageFileSize = new ArrayList<>();
// Code to add data to ArrayLists (data is not coming from sqlite database)
...
// Code to sort arrPackage alphabatically with case ignored
Collections.sort(arrPackage, new Comparator<String>() {
#Override
public int compare(String s1, String s2) {
return s1.compareToIgnoreCase(s2);
}
});
but how do I know which indexes were changed?
One approach would be to create a wrapper object Package which contains the four types of metadata which appears in the four current lists. Something like this:
public class Package {
private String name;
private String date;
private String duration;
private String fileSize;
public Package() {
// can include other constructors as well
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
// other getters and setters
}
Then sort using a custom comparator which works on Package objects:
List<Package> packages = new ArrayList<>();
Collections.sort(packages, new Comparator<Package>() {
#Override
public int compare(Package p1, Package p2) {
String name1 = p1.getName();
String name2 = p2.getName();
return name1.compareToIgnoreCase(name2);
}
});
As a general disclaimer, the above operation would most likely be performed must more efficiently in a database. So if your data is ultimately coming from a database, you should try to do such heavy lifting there.
A simple easy way would be backing up your ArrayList.
ArrayList<String> backupPackage = arrPackage;
And then use your code to sort the array. Then use a for loop to compare the two arrays.
for (int i = 0; i < backupArray.size(); i++) {
if (!aar.get(i).equals(aar.get(i))) { // then the item has been changed
// ... YOUR CODE
// at this point you know which indexes have been changed and can modify your other arrays in any way you need
}
}
I used this approach:
ArrayList<String> backupPackage = new ArrayList<>();
ArrayList<String> backupPackageDates = new ArrayList<>();
ArrayList<String> backupPackageDuration = new ArrayList<>();
ArrayList<String> backupPackageFileSize = new ArrayList<>();
for(int j=0;j<arrPackage.size();j++) {
backupPackage.add(arrPackage.get(j));
}
for(int j=0;j<arrPackageDates.size();j++) {
backupPackageDates.add(arrPackageDates.get(j));
}
for(int j=0;j<arrPackageDuration.size();j++) {
backupPackageDuration.add(arrPackageDuration.get(j));
}
for(int j=0;j<arrPackageFileSize.size();j++) {
backupPackageFileSize.add(arrPackageFileSize.get(j));
}
Collections.sort(arrPackage, new Comparator<String>() {
#Override
public int compare(String s1, String s2) {
return s1.compareToIgnoreCase(s2);
}
});
int newindex;
for(int i=0; i<backupPackage.size(); i++) {
newindex = backupPackage.indexOf(arrPackage.get(i));
if(newindex != i) {
arrPackageDates.set(i, backupPackageDates.get(newindex));
arrPackageDuration.set(i, backupPackageDuration.get(newindex));
arrPackageFileSize.set(i, backupPackageFileSize.get(newindex));
}
}
backupPackage.clear();
backupPackageDuration.clear();
backupPackageDuration.clear();
backupPackageFileSize.clear();

Using information from object selected in jList

I am having difficulty getting information from a jList so that it can be used to create an object in a different class when a button is clicked,
private void jButtonAddOrderActionPerformed(java.awt.event.ActionEvent evt) {
int noCopies;
String title, Name;
noCopies = Integer.parseInt(jTextFieldCopies.getText());
title = Book.bookInstances.get(jListPubBooks.getSelectedIndex()).getName();
Name = Book.bookInstances.get(jListPubBooks.getSelectedIndex()).getPublisherName();
new Order(noCopies, title, Name);
setjlistmodel(Order.orderItem);
I am sure there are no problems with my setjlistmodel method as this works elsewhere in my program when only getting information from text fields. I think my problem is with these two lines:
title = Book.bookInstances.get(jListPubBooks.getSelectedIndex()).getName();
Name = Book.bookInstances.get(jListPubBooks.getSelectedIndex()).getPublisherName();
}
This is my order class;
package bookstore;
import java.util.ArrayList;
public class Order {
int noOfBooks;
String bookTitle;
String pubName;
public static ArrayList<Order> orderItem = new ArrayList<>();
ArrayList<ArrayList<Order>> Order = new ArrayList<>();
public Order(int noBooks, String Title, String Name)
{
this.noOfBooks = noBooks;
this.bookTitle = Title;
this.pubName = Name;
orderItem.add(this);
}
public void addOrder(ArrayList ord)
{
Order.add(ord);
}
public int getNoBooks()
{
return noOfBooks;
}
public String getBookTitle()
{
return bookTitle;
}
public String getPubName()
{
return pubName;
}
}
setjlistmodel method:
private void setjlistmodel(ArrayList<Order> orderInstances){
DefaultListModel OrderList = new DefaultListModel();
for(int i = 0; i<=OrderList.size()-1;i++){
OrderList.addElement(orderInstances.get(i).getNoBooks());
System.out.println(orderInstances.get(i).getBookTitle());
System.out.println(OrderList.firstElement());
}
jListOrder.setModel(OrderList);
}
The problem is that it is not displaying anything in jListOrder when the button is clicked. I don't think the Order is being added to the orderItem ArrayList.
"The problem is that it is not displaying anything in jListOrder when the button is clicked. I don't think the Order is being added to the orderItem ArrayList."
I think adding an orderItem is fine.
OrderList size is zero when you first initialize it, which means your loops does absolutely nothing
DefaultListModel OrderList = new DefaultListModel();
for(int i = 0; i <= OrderList.size() - 1; i++)
You probably want
for(int i = 0; i <= orderInstances.size() - 1; i++)
Which is using the ArrayList size.
As a side note, please separate operators with space. It makes it easier to read.

Categories

Resources