So, I'm trying to figure out how to get values of an array list from another class and print certain values depending on user input.
For example, firstly a user is asked to provide a location, once they enter a location, it has to read the user input and output the results according to the location.an image is provided about the output.
For some reason it doesn't output the correct values from array list.
Could you please help me out?
This is my code for reading values from array list.
public class Program {
ArrayList<Properties> property = Properties.getMelbnbProperty();
int i = 1;
for(i = 1; i < (property.size());) {
System.out.println(property.get(i));
break;
}
ArrayList<Properties> output = Properties.getMelbnbProperty();
if(Properties.getMelbnbProperty().contains(choice)) {
output.addAll(Properties.getMelbnbProperty());
}
} }
This is my code for array list.
public class Properties {
public static ArrayList<Properties> getMelbnbProperty() {
// Below is an arraylist where I have stored the Melbnb data
ArrayList<Properties> property = new ArrayList<Properties>();
property.add(new Properties("Private room in the heart of Southbank"));
property.add(new Properties("Spacious bedroom in a cosy apartment in South Yarra\n"));
property.add(new Properties("Ensuite room with great views"));
property.add(new Properties("Single room next to Carlton Gardens"));
property.add(new Properties("Studio close to Melbourne CBD"));
property.add(new Properties("1-bedroom CBD view suite near Melbourne Central and RMIT"));
property.add(new Properties("Stylish two bedroom in CBD"));
property.add(new Properties("Sky high studio with amazing views"));
property.add(new Properties("Budget accommodation bunk beds"));
property.add(new Properties("A beautiful room near Marvel Stadium"));
return property;
}}
The code you have provided in your question post is incomplete and in a way doesn't make sense to what your image displays. I do however understand what you are trying to accomplish but the way I see it your properties class is somewhat under-nourished.
I don't know if this is the intentional purpose but your for loop:
int i = 1;
for(i = 1; i < (property.size());) {
System.out.println(property.get(i));
break;
}
is designed to pull out 1 object from the property ArrayList. This loop is completely unnecessary since just supplying an index value of 1 to the ArrayList#get() method does exactly the same thing and is only a single line of code, for example:
System.out.println(property.get(1));
I say this because your for loop initializer starts at index 1, there is no iterator for the loop, and you apply the break statement directly after the display of the object within the ArrayList.
To access all elements within the ArrayList (your post indicates) you would need to do something like this:
for (int i = 0; i < properties.size(); i++) {
System.out.println(properties.get(i));
}
Or you can use:
for (String props: properties) {
System.out.println(props);
}
To be honest, what you are showing for code in grossly underdeveloped. I don't want to come across as insulting but it's obvious that you are not showing as much as you should be and therefore it is extremely difficult to provide you with any concrete solution to your problem. For this reason, I think it is just easier to provide you with a working demo console application which would allow you to perhaps grasp some concepts from.
The runnable code below consists of two specific classes, the start up class named SimpleBNBDemo which contains the main() method and the Properties class which allows you to instantiate instances of different BNB properties. As you can see, the Properties class is somewhat more fulfilled than the class you provided in your question post. Take the time to read through the code and try to follow its flow. Do keep in mind, although runnable this is only a Demo application and is in now way a complete works. I personally would never hard-code fill an ArrayList with Object data. This data should come from and or saved to a file system or database. However, for demo purposes this will suffice.
The SimpleBNBDemo class:
public class SimpleBNBDemo {
// Field variables
public final static String LS = System.lineSeparator();
public final static java.util.Scanner USER_INPUT = new java.util.Scanner(System.in);
// class member variable
private Properties prop = new Properties();
private final String line = "------------------------------------------------";
private int pwAttempts = 0;
public static void main(String[] args) {
// Started this way to avoid the need for statics
new SimpleBNBDemo().startApp(args);
}
private void startApp(String[] args) {
/* Create Properties instances...
You can do this with whatever means you like. */
java.util.List<Properties> properties = prop.getProperties();
properties.add(new Properties("Southbank Mannor", "Room", "Private room in the heart of Southbank.", "South", 86.00d, true));
properties.add(new Properties("Yarra House", "Room", "Spacious bedroom in a cosy apartment in South Yarra.", "South", 74.00d, true));
properties.add(new Properties("Ensuite Haven", "Room", "Ensuite room with great views.", "West", 65.50d, true));
properties.add(new Properties("Carlton Place", "Room", "Single room next to Carlton Gardens.", "South", 78.00d, true));
properties.add(new Properties("Melbourne Studio", "Studio", "Studio close to Melbourne CBD.", "East", 78.00d, true));
properties.add(new Properties("Melbourne Delight", "Room", "1-bedroom CBD view suite near Melbourne Central and RMIT.", "North", 135.00d, true));
properties.add(new Properties("CBD House", "Suit", "Stylish two bedroom in CBD.", "West", 100.00d, true));
properties.add(new Properties("Sky-High", "Studio", "Sky high studio with amazing views.", "North", 95.00d, true));
properties.add(new Properties("Budgeteer", "Room", "Budget accommodation bunk beds.", "South", 65.00d, true));
properties.add(new Properties("Stadium House", "Room", "A beautiful room near Marvel Stadium.", "East", 95.00d, true));
println("Welcome to MelBNB" + LS + line);
println();
// Menu 1 - Main Menu
String choice = "";
String[] locations = prop.getAllLocations();
if (locations.length == 0) {
printErr("No BNB's with Location in database yet!");
return;
}
while (choice.isEmpty()) {
println("Select from Main Menu:");
println(" 1) List all Accomodations");
println(" 2) Search by location");
println(" 3) Browse by type of accomodation");
println(" 4) Filter by rating");
println(" 5) Rate an accomodation");
println(" 6) Exit (quit)");
print("Please choose: -> ");
choice = USER_INPUT.nextLine().trim();
// Validate Entry...switch/case works great for input validation.
switch (choice) {
case "1":
listAllAccomodations();
break;
case "2":
searchByLocation();
break;
case "3":
searchByAccomodationType();
break;
case "4":
searchByRating();
break;
case "5":
rateAnAccomodation();
break;
case "6":
break;
case "~admin~":
adminMenu();
break;
case "~admin attempts reset~":
pwAttempts = 0;
println();
break;
default:
println("Invalid Entry (" + choice + ")! Try again..." + LS);
}
// Was 'Exit' (4) selected?
if (choice.equals("6")) {
// Break out of loop to end application.
println(LS + "Thank you for visiting MelBNB, Bye-Bye." + LS);
break;
}
choice = ""; // Reset 'choice' to be empty in order to loop again..
}
}
private void adminMenu() {
String pwrd = "";
while (pwrd.isEmpty()) {
if (pwAttempts >= 3) {
println(LS + "Admin Menu is NOT Available!" + LS + "To many failed "
+ "consecutive password attempts!" + LS + "Only " + pwAttempts
+ " consecutive attempts are allowed." + LS);
return;
}
print(LS + "Please enter Admin Password (c to cancel): --> ");
pwrd = USER_INPUT.nextLine().trim();
if (pwrd.equalsIgnoreCase("c")) {
println();
return;
}
int psum = 0;
for (int i = 0; i < pwrd.length(); i++) {
psum += pwrd.charAt(i);
}
if (psum != 624) {
pwAttempts++;
println("Invalid Password! Try again...");
pwrd = "";
}
}
pwAttempts = 0;
println();
println("***********************************************");
println("*** Administrative options would go here! ***");
println("*** Press Enter To Continue ***");
println("***********************************************");
String nothing = USER_INPUT.nextLine().trim();
}
private void listAllAccomodations() {
println(LS + "All Available Accomodations:");
println("----------------------------");
int cntr = 0;
String underline = "";
for (Properties pp : prop.getProperties()) {
cntr++;
String str = pp.toStringTable(pp, cntr == 1);
underline = String.join("", java.util.Collections.nCopies(str.length(), "="));
println(str);
if (cntr == 15) {
println("<- Press Enter To Continue ->");
String nuthin = USER_INPUT.nextLine().trim();
cntr = 0;
}
}
println(underline + LS);
}
private void searchByLocation() {
String[] locationTypes = prop.getAllLocations();
java.util.Arrays.sort(locationTypes);
String locationChoice = "";
while (locationChoice.isEmpty()) {
println();
println("Select the desired location:");
int i = 0;
for ( ; i < locationTypes.length; i++) {
println(" " + (i + 1) + ") " + locationTypes[i]);
}
println(" " + (i + 1) + ") Cancel");
print("Please choose: -> ");
locationChoice = USER_INPUT.nextLine().trim();
// Validate Entry...
if (!locationChoice.matches("[1-" + (locationTypes.length + 1) + "]")) {
println("Invalid Entry (" + locationChoice + ")! Try again..." + LS);
locationChoice = "";
}
}
if (locationChoice.equals(String.valueOf(locationTypes.length + 1))) {
println();
return;
}
String location = locationTypes[Integer.valueOf(locationChoice)-1];
java.util.List<Properties> p = prop.getPropertiesByLocation(location);
if (p.isEmpty()) {
println("No accomodations available in the " + location + " area!" + LS);
return;
}
String str = "Available accomodation within the " + location + " area:";
println(LS + str);
println(String.join("", java.util.Collections.nCopies(str.length(), "-")));
int cntr = 0;
for (Properties pp : p) {
cntr++;
println(pp.toStringTable(pp, cntr == 1));
}
println(line + LS);
}
private void searchByAccomodationType() {
String[] accTypes = prop.getAllAccomodationTypes();
java.util.Arrays.sort(accTypes);
String accChoice = "";
while (accChoice.isEmpty()) {
println();
println("Select the desired accomodation type:");
int i = 0;
for ( ; i < accTypes.length; i++) {
println(" " + (i + 1) + ") " + accTypes[i]);
}
println(" " + (i + 1) + ") Cancel");
print("Please choose: -> ");
accChoice = USER_INPUT.nextLine().trim();
// Validate Entry...
if (!accChoice.matches("[1-" + (accTypes.length + 1) + "]")) {
println("Invalid Entry (" + accChoice + ")! Try again..." + LS);
accChoice = "";
}
}
if (accChoice.equals(String.valueOf(accTypes.length + 1))) {
println();
return;
}
String acc = accTypes[Integer.valueOf(accChoice)-1];
java.util.List<Properties> p = prop.getPropertiesByAccomodationType(acc);
if (p.isEmpty()) {
println("No accomodation type of " + acc + " is available!" + LS);
return;
}
String str = "Available accomodation that are of type '" + acc + "':";
println(LS + str);
println(String.join("", java.util.Collections.nCopies(str.length(), "-")));
int cntr = 0;
for (Properties pp : p) {
cntr++;
println(pp.toStringTable(pp, cntr == 1));
}
println(line + LS);
}
private void searchByRating() {
String rateChoice = "";
while (rateChoice.isEmpty()) {
println();
println("Enter the desired accomodation rating (1 to 5);");
print( "Enter c to cancel. Desired Rating: --> ");
rateChoice = USER_INPUT.nextLine().trim();
if (rateChoice.equalsIgnoreCase("c")) {
return;
}
// Validate Entry...
if (!rateChoice.matches("[1-5]")) {
println("Invalid Entry (" + rateChoice + ")! Try again..." + LS);
rateChoice = "";
}
}
int rating = Integer.valueOf(rateChoice);
java.util.List<Properties> p = prop.getPropertiesByRating(rating);
if (p.isEmpty()) {
println("No accomodation available with the rating of " + rating + "!" + LS);
return;
}
String str = "Available accomodation with a rating of '" + rating + "':";
println(LS + str);
println(String.join("", java.util.Collections.nCopies(str.length(), "-")));
int cntr = 0;
for (Properties pp : p) {
cntr++;
println(pp.toStringTable(pp, cntr == 1));
}
println(line + LS);
}
private void rateAnAccomodation() {
/* Displayed ratings are always the AVERAGE of all ratings
provided for that particular propety. This is done within
the 'Properties.addRating()' method. For this reason and
for other obvious reasons the Properties List should be
saved to either a file or a database. If this is not done
then all added or modified data will be lost when the
application closes. The Properties List data should NOT
be hard-coded. It should be loaded in when the application
starts and saved to storage when data is added or modified.
*/
String[] pNames = prop.getAllPropertyNames();
String nameToRate = "";
while (nameToRate.isEmpty()) {
println(LS + "Enter the name of the accomodation you want to rate:");
print( "Enter 'c' to cancel. Rating: --> ");
nameToRate = USER_INPUT.nextLine().trim();
if (nameToRate.equalsIgnoreCase("c")) {
return;
}
// Validate Entry............................
if (nameToRate.isEmpty()) {
println("Invalid Entry! You must enter a Name! Try again...");
nameToRate = "";
continue;
}
// Does the name exist in List?
boolean found = false;
for (String name : pNames) {
if (name.equalsIgnoreCase(nameToRate)) {
// Yes it does...
found = true;
break; // Break out of this loop.
}
}
if (!found) {
println("Invalid Entry (" + nameToRate + ")!" + LS
+ "Can not find the name supplied! Try again..." + LS);
nameToRate = "";
}
}
//.................................................
/* If we get to here then the name supplied
(regarless of letter case) is in the List. */
String rateNum = "";
while (rateNum.isEmpty()) {
println();
print("Enter your rating (1 to 5 or 'c' to cancel): --> ");
rateNum = USER_INPUT.nextLine().trim();
if (rateNum.equalsIgnoreCase("c")) {
return;
}
// Validate Entry...
if (!rateNum.matches("[1-5]")) {
println("Invalid Entry (" + rateNum + ")! Try again..." + LS);
rateNum = "";
}
println();
}
// Set the rating.
int rating = Integer.valueOf(rateNum);
for (Properties p : prop.getProperties()) {
if (p.getPropertyName().equalsIgnoreCase(nameToRate)) {
int avgRating = p.getAverageRating();
p.addRating(rating);
println("Your rating of " + rating + " has been added to the accomodation" + LS
+ "named '" + nameToRate + "' which has moved its overall rating" + LS
+ "average from " + avgRating + " to an overall average rating of " +
p.getAverageRating() + "." + LS + "This is based on " +
p.getTotalNumberOfRatingsDone() + " rating(s) on the accomodation." + LS);
}
}
}
public static void println(Object... obj) {
if (obj.length > 0) {
System.out.println(obj[0]);
}
else {
System.out.println();
}
}
public static void printErr(Object... obj) {
if (obj.length > 0) {
System.err.println(obj[0]);
}
else {
System.err.println();
}
}
public static void print(Object... obj) {
if (obj.length > 0) {
System.out.print(obj[0]);
}
else {
System.out.print("");
}
}
}
The Properties class:
public class Properties {
public static java.util.List<Properties> properties = new java.util.ArrayList<>();
private String propertyName;
private String accomodationType;
private String description;
private String location;
private double pricePerDay;
private int averageRating = 0;
private int totalNumberOfRatings;
private boolean available;
// Constructor #1
public Properties() { }
// Constructor #2
public Properties(String propertyName, String accomodationType, String description,
String location, double pricePerDay, boolean available) {
this.propertyName = propertyName;
this.accomodationType = accomodationType;
this.description = description;
this.location = location;
this.pricePerDay = pricePerDay;
this.available = available;
}
// Getters & Setters
public java.util.List<Properties> getProperties() {
return properties;
}
public String getPropertyName() {
return propertyName;
}
public void setPropertyName(String propertyName) {
this.propertyName = propertyName;
}
public String getAccomodationType() {
return accomodationType;
}
public void setAccomodationType(String accomodationType) {
this.accomodationType = accomodationType;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public double getPricePerDay() {
return pricePerDay;
}
public void setPricePerDay(double pricePerDay) {
this.pricePerDay = pricePerDay;
}
public int getAverageRating() {
return this.averageRating;
}
public void addRating(int rating) {
// Rateing is an integer value from 1 to 5.
// Where 1 is Bad and 5 Excellent.
if (rating < 1) { rating = 1; }
else if (rating > 5) { rating = 5; }
int sum = 0, r = 0;
for (Properties p : properties) {
if (p.propertyName.equalsIgnoreCase(this.propertyName)) {
r++;
sum += rating;
}
}
if (sum > 0 && r > 0) {
this.averageRating = sum / r;
}
else {
this.averageRating = rating;
}
this.totalNumberOfRatings++;
}
public boolean isAvailable() {
return available;
}
public void setAvailable(boolean available) {
this.available = available;
}
#Override
public String toString() {
return propertyName + ", " + accomodationType + ", " + description + ", "
+ location + ", " + pricePerDay + ", " + averageRating + ", "
+ available;
}
public String toStringTable(Properties p, boolean... addHeader) {
boolean applyHeader = false;
if (addHeader.length > 0) {
applyHeader = addHeader[0];
}
String symbol = java.util.Currency.getInstance(java.util.Locale.getDefault()).getSymbol();
String header = "", underline = "", ls = System.lineSeparator();
StringBuilder sb = new StringBuilder("");
header = String.format("%-18s %-10s %-50s %-10s %-10s %-8s %-6s%n", "BNB Name",
"BNB Type", "BNB Description", "Location", "Price/Day", "Rating", "Avail.");
underline = String.join("", java.util.Collections.nCopies(header.length(), "=")) + ls;
if (applyHeader) {
sb.append(header).append(underline);
}
String[] desc = p.description.split("\\s+");
java.util.List<String> descTmp = new java.util.ArrayList<>();
StringBuilder sb2 = new StringBuilder("");
for (String str : desc) {
if ((sb2.toString() + " " + str).length() > 50) {
descTmp.add(sb2.toString());
sb2.setLength(0);
}
if (!sb2.toString().isEmpty()) {
sb2.append(" ");
}
sb2.append(str);
}
if (!sb2.toString().isEmpty()) {
descTmp.add(sb2.toString());
}
sb.append(String.format("%-18s %-10s %-50s %-12s " + symbol + "%-10.2f %-7s %-6s",
p.propertyName, p.accomodationType, descTmp.get(0), p.location,
p.pricePerDay, p.averageRating, (p.available ? "Yes" : "No")));
if (descTmp.size() > 1) {
for (int i = 1; i < descTmp.size(); i++) {
sb.append(ls).append(String.format("%-18s %-10s %-50s %-12s %-10s %-7s %-6s",
" "," ", descTmp.get(i), " ", " ", " ", " "));
}
}
return sb.toString();
}
public String[] getAllPropertyNames() {
java.util.List<String> tmp = new java.util.ArrayList<>();
for (Properties prop : properties) {
// Make sure names retrieved are Unique (DISTINCT)
if (!tmp.contains(prop.propertyName)) {
tmp.add(prop.propertyName);
}
}
return tmp.toArray(new String[tmp.size()]);
}
public String[] getAllAccomodationTypes() {
java.util.List<String> tmp = new java.util.ArrayList<>();
for (Properties prop : properties) {
// Make sure accomodations retrieved are Unique (DISTINCT)
if (!tmp.contains(prop.accomodationType)) {
tmp.add(prop.accomodationType);
}
}
return tmp.toArray(new String[tmp.size()]);
}
public java.util.List<Properties> getPropertiesByLocation(String location) {
java.util.List<Properties> tmp = new java.util.ArrayList<>();
for (Properties p : Properties.properties) {
if (p.location.equalsIgnoreCase(location) && !tmp.contains(p)) {
tmp.add(p);
}
}
return tmp;
}
public java.util.List<Properties> getPropertiesByAccomodationType(String accomodationType) {
java.util.List<Properties> tmp = new java.util.ArrayList<>();
for (Properties p : Properties.properties) {
if (p.accomodationType.equalsIgnoreCase(accomodationType) && !tmp.contains(p)) {
tmp.add(p);
}
}
return tmp;
}
public java.util.List<Properties> getPropertiesByRating(int rating) {
java.util.List<Properties> tmp = new java.util.ArrayList<>();
for (Properties p : Properties.properties) {
if (p.averageRating == rating && !tmp.contains(p)) {
tmp.add(p);
}
}
return tmp;
}
public int getTotalNumberOfRatingsDone() {
return this.totalNumberOfRatings;
}
public String[] getAllDescriptions() {
java.util.List<String> tmp = new java.util.ArrayList<>();
for (Properties prop : properties) {
// Make sure descriptions retrieved are Unique (DISTINCT)
if (!tmp.contains(prop.description)) {
tmp.add(prop.description);
}
}
return tmp.toArray(new String[tmp.size()]);
}
public String[] getAllLocations() {
java.util.List<String> tmp = new java.util.ArrayList<>();
for (Properties prop : properties) {
// Make sure locations retrieved are Unique (DISTINCT)
if (!tmp.contains(prop.location)) {
tmp.add(prop.location);
}
}
return tmp.toArray(new String[tmp.size()]);
}
public double[] getAllPerDayPrices() {
java.util.List<Double> tmp = new java.util.ArrayList<>();
for (Properties prop : properties) {
// Make sure locations retrieved are Unique (DISTINCT)
if (!tmp.contains(prop.pricePerDay)) {
tmp.add(prop.pricePerDay);
}
}
// Convert List<Double> to double[]...
double[] prices = new double[tmp.size()];
for (int i = 0; i < tmp.size(); i++) {
prices[i] = tmp.get(i);
}
return prices;
}
}
I have two lists with with the same data except the first list might have slightly different wording.
I am making sure the fields dont match. If they dont, then i add a plus to the first word in the array and a minus to the second word in the second array.
I am just iterating over the list and i have a ton of ifs. There are other data points i will need to do also and the ifs can get very long. Is there a more efficient way of doing this?
I am not good with java 8+ and streams. Would it be better to do it with streams and if so how would i do this? Could you please do an example?
Thank you in advance!!! I really need help but i am expecting to get my heart broken!
List<ExteriorColor> f1 = vinResponseOne.getResult().getExteriorColors();
List<ExteriorColor> f2 = vinResponseTwo.getResult().getExteriorColors();
first = vinResponseOne.getResult().getExteriorColors();
second = vinResponseTwo.getResult().getExteriorColors();
private void compareExteriorColors(List<ExteriorColor> f1, List<ExteriorColor> f2){
for(int i =0; i< f1.size(); i++) {
if (!f1.get(i).getDescription().equals(f2.get(i).getDescription())) {
final String added = "+ " + f1.get(i).getDescription();
final String original = "- " + f2.get(i).getDescription();
first.get(i).setDescription(added);
second.get(i).setDescription(original);
}
if (!f1.get(i).getGenericDesc().equals(f2.get(i).getGenericDesc())) {
final String added = "+ " + f1.get(i).getGenericDesc();
final String original = "- " + f2.get(i).getGenericDesc();
first.get(i).setGenericDesc(added);
second.get(i).setGenericDesc(original);
}
if (!f1.get(i).getColorCode().equals(f2.get(i).getColorCode())) {
final String added = "+ " + f1.get(i).getColorCode();
final String original = "- " + f2.get(i).getColorCode();
f1.get(i).setColorCode(added);
f2.get(i).setColorCode(original);
}
if (f1.get(i).getInstallCause() != null) {
if (!f1.get(i).getInstallCause().equals(f2.get(i).getInstallCause())) {
final String added = "+ " + f1.get(i).getInstallCause();
final String original = "- " + f2.get(i).getInstallCause();
first.get(i).setInstallCause(added);
second.get(i).setInstallCause(original);
}
}
if (!f1.get(i).getPrimary().equals(f2.get(i).getPrimary())) {
final String added = "+ " + f1.get(i).getPrimary();
final String original = "- " + f2.get(i).getPrimary();
first.get(i).setPrimary(added);
second.get(i).setPrimary(original);
}
if (!f1.get(i).getRgbValue().equals(f2.get(i).getRgbValue())) {
final String added = "+ " + f1.get(i).getRgbValue();
final String original = "- " + f2.get(i).getRgbValue();
first.get(i).setRgbValue(added);
second.get(i).setRgbValue(original);
}
if (!f1.get(i).getStyles().equals(f2.get(i).getStyles())) {
List<String> styleFirst = new ArrayList<>();
List<String> styleSecond = new ArrayList<>();
final String added = "+ " + f1.get(i).getStyles();
final String original = "- " + f2.get(i).getStyles();
styleFirst.add(added);
styleSecond.add(original);
first.get(i).setStyles(styleFirst);
second.get(i).setStyles(styleSecond);
}
if (!f1.get(i).getType().equals(f2.get(i).getType())) {
String added = "+ " + f1.get(i).getType();
String original = "- " + f2.get(i).getType();
first.get(i).setType(added);
second.get(i).setType(original);
}
}
}
What it ends up looking like.
I will later convert to json.
class User { //Considering a simple class with only 2 fields for brevity
private String userName;
private String password;
User(String userName, String password) {
this.userName = userName;
this.password = password;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Override
public String toString() {
return "User{" + "userName='" + userName + '\'' + ", password='" + password + '\'' + '}';
}
}
public class S14 {
public static void main(String[] args) {
User user1 = new User("Anees", "pwd");
User user2 = new User("Anees1", "pwd");
List<User> userList1 = new ArrayList<>(Arrays.asList(user1, user2));
User user3 = new User("Anees2", "pwd");
User user4 = new User("Anees3", "pwd");
List<User> userList2 = new ArrayList<>(Arrays.asList(user3, user4));
// Assuming both Lists are of same size
IntStream.range(0, userList1.size())
.forEach(
i -> {
User firstListUser = userList1.get(i);
User secondListUser = userList2.get(i);
//HERE GOES THE MAIN PART
compareStringsAndProcessElement(
firstListUser::getUserName,
secondListUser::getUserName,
(s, s2) -> !s.equals(s2),
firstListUser::setUserName,
secondListUser::setUserName);
compareStringsAndProcessElement(
firstListUser::getPassword,
secondListUser::getPassword,
(s, s2) -> !s.equals(s2),
firstListUser::setPassword,
secondListUser::setPassword);
//AND SO ON!
});
System.out.println(userList1);
System.out.println(userList2);
}
private static void compareStringsAndProcessElement(
Supplier<String> element1,
Supplier<String> element2,
BiPredicate<String, String> stringStringBiPredicate,
Consumer<String> u1,
Consumer<String> u2) {
String e1 = element1.get();
String e2 = element2.get();
if (stringStringBiPredicate.test(e1, e2)) {
e1 = "+" + e1;
e2 = "-" + e2;
u1.accept(e1);
u2.accept(e2);
}
}
}
Hope this helps! This has nothing fancy with Streams, but uses Functional approach for a problem instead of your declarative one. This could be written with Normal loops too instead of IntStream.
PS: As far as performance goes, this might be even slower than declarative implementation since it involves multiple method calls. But, saving off some nanoseconds is not a good trade-off than code maintainability.
How to convert the string back to object? I have the following class:
class Test {
String name;
String value;
String testing;
#Override
public String toString() {
return "Test{" +
"name='" + name + '\'' +
", value='" + value + '\'' +
", testing='" + testing + '\'' +
'}';
}
}
class Testing {
private List<Test> testing = new ArrayList<Test>();
handling(testing.toString())
public String handling(String testing) {
// do some handling and return a string
}
}
ArrayList testing must handled by convert to string, for example, after that, we get the following string:
[Test{name='name1', value='value1', testing='testing1'}, Test{name='name2', value='value2', testing='testing2'}, Test{name='name3', value='value3', testing='testing3'}]
then how to convert the string back to object list of Test?
Can anyone help on it?
If you don't need exactly that toString pattern, but only need to convert your Object to something human-readable and than back to an Object, you could marshal to json and parse back to Object seamlessly with something like Jackson ObjectMapper. See https://www.baeldung.com/jackson-object-mapper-tutorial for a quick-start.
You can create an additional constructor and call them with the string:
class Test {
private String name;
private String value;
private String testing;
Test(string objString) {
Pattern pattern = Pattern.compile("name=('.+'), value=('.+'), testing=('.+')");
Matcher matcher = pattern.matcher(objString);
if (matcher.matches()) {
name = matcher.group(1);
value = matcher.group(2);
testing = matcher.group(3);
} else {
throw new ArgumentException("Cannot parse"):
}
}
#Override
public String toString() {
return "Test{" +
"name='" + name + "'" +
", value='" + value + "'" +
", testing='" + testing + "'" +
'}';
}
}
class Testing {
doTesting(List<Test> testing) {
List<String> testingAsString = new ArrayList<String>();
// To string
for (Test t : testing) {
testingAsString.add(t.toString());
}
List<Test> clonedTesting = new ArrayList<Test>();
// To Test
for (String t : testingAsString) {
clonedTesting.add(new Test(t));
}
// Here every test string is again an object of type Test
for (Test t : clonedTesting) {
System.out.println(t);
}
}
}
I have a scenario where I need to fetch 500 from web service api and display the final output values as comma separated values like id,name,owner,account,path,ccvalues. To achieve this I am writing a method where Iam getting all this information and setting to one java object. Fields are below. Finally i created one list which holds this Video objects. videos.add(video)
String identifier;
String name;
String ownerName;
String accountName;
String mediaPath;
List<KalturaLanguage> ccList;
Now how to display my output from videos list object. Please help me resolving this.
code is:
for (String mediaId : mediaList) {
if (mediaId != null) {
String mediaFullPath = getMediaPath(mediaId);
entryInfo = getMedia(mediaId);
metadataList = getMetadata(mediaId);
ccs = getClosedCaptions(mediaId);
if (entryInfo != null) {
video = new Video();
System.out.println("entryInfo.id"
+ entryInfo.id);
System.out.println("entryInfo.name"
+ entryInfo.name);
System.out.println("mediaFullPath"
+ mediaFullPath);
video.setIdentifier(entryInfo.id);
video.setName(entryInfo.name);
video.setMediaPath(mediaFullPath);
}
if (metadataList != null
&& metadataList.totalCount != 0) {
List<KalturaMetadata> metadataObjs = metadataList.objects;
if (metadataObjs != null
&& metadataObjs.size() > 0) {
for (int i = 0; i < metadataObjs.size(); i++) {
KalturaMetadata metadata = metadataObjs
.get(i);
if (metadata != null) {
if (metadata.xml != null) {
metadataValues = parseXml(metadata.xml);
if (metadataValues.size() != 0) {
ibmAccountList = metadataValues
.get(0);
for (String account : ibmAccountList) {
System.out
.println("IBM Account Name ------->"
+ account);
video.setAccountName(account);
}
ownerList = metadataValues
.get(1);
for (String owner : ownerList) {
System.out
.println("Account Owner Name ------->"
+ owner);
video.setOwnerName(owner);
}
}
}
}
}
}
}
}
if (ccs.size() != 0) {
for (Map.Entry<String, List<KalturaCaptionAsset>> entry : ccs
.entrySet()) {
String key = entry.getKey();
List<KalturaCaptionAsset> values = entry
.getValue();
// System.out.println("Key = " + key);
for (KalturaCaptionAsset asset : values) {
System.out.println(" CC value : "
+ asset.language);
ccList.add(asset.language);
video.setCcList(ccList);
videos.add(video);
}
}
}
}
You are going in a wrong direction. Just implement your toString method inside Video class.
When you iterate over list and print video object it calls toString method inside the video class.
While providing implementation in video class, generate a String in required format.
Beginner programmer here.
I have to append strings of file names together and have come up with the following methods:
class ConsLoItem implements ILoItem {
Item first;
ILoItem rest;
ConsLoItem(Item first, ILoItem rest) {
this.first = first;
this.rest = rest;
}
public String images() {
if (this.rest.equals(new MtLoItem()))
{
return this.first.images();
}
else
return this.first.images() + ", " + this.rest.images();
}
}
and keep getting the same results, with:
", jesse.jpeg, " when I expect "jesse.jpeg".
Any ideas on how to remove the ", " from the beginning and end of the file name?
You can change your images method, like so
public String images() {
if (this.rest.equals(new MtLoItem())) {
return this.first.images();
} else { // missed a brace here.
if (this.first.images().length() > 0) {
return this.first.images() + ", " + this.rest.images();
}
return this.rest.images();
}
}