Java List Sorting [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
public class Lot implements Listable {
int EmpID;
String Ename;
double Sal;
public Lot(int id,String ename, double sal) {
this.EmpID = id;
this.Ename = ename;
this.Sal = sal;
}
public int getEmpID() {
return EmpID;
}
public String getEname() {
return Ename;
}
public double getSal() {
return Sal;
}
public String toString() {
return "ID - " + EmpID + "\n" + "Name - " + Ename + "\n" + "Salary - " + Sal;
}
#Override
public int compareTo(Listable otherList) {
Lot other = (Lot)otherList;
return (this.EmpID - other.EmpID);
}
}
Main Class :
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class SortTest {
public static void main(String[] args) {
List list = new ArrayList();
list.add(new Lot(4, "aaa", 12000));
list.add(new Lot(3, "bbb", 1000));
list.add(new Lot(1, "ccc", 8000));
list.add(new Lot(2, "ddd", 2500));
Collections.sort(list); //ERROR
}
}
This gives an Error 'Lot cannot be cast to java.lang.Comparable'
What is the mistake...

Create a Class which implements Comparable interface like below :
public class Lot implements Comparable<Lot> {
private int lotNumber;
private String firstName;
private String lastName;
private BigDecimal price;
private Long squareFeet;
private int numberofBedRooms;
public int getLotNumber() {
return lotNumber;
}
public void setLotNumber(int lotNumber) {
this.lotNumber = lotNumber;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public Long getSquareFeet() {
return squareFeet;
}
public void setSquareFeet(Long squareFeet) {
this.squareFeet = squareFeet;
}
public int getNumberofBedRooms() {
return numberofBedRooms;
}
public void setNumberofBedRooms(int numberofBedRooms) {
this.numberofBedRooms = numberofBedRooms;
}
#Override
public int compareTo(Lot lot) {
return this.lotNumber - lot.lotNumber;
}
}
After this create a List of this object with all the values populated and use Collections.sort(---).

I just add the instruction not the code implementation -
Create a class Lot with lotNum and other property. Implement the interface comparable interface for this class.
Add all these lot to collection like ArrayList - lotList
Now call the Collections.sort()
Hope it will help.
Thanks a lot.

An example of how you can do :
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class TestJava {
public static void main(String[] args) throws java.text.ParseException {
List<Lot> lots = new ArrayList<Lot>();
lots.add(new Lot(2, "bbb", "ccc", "bbb", "sss", "ccc"));
lots.add(new Lot(4, "bbb", "ccc", "bbb", "sss", "ccc"));
lots.add(new Lot(3, "bbb", "ccc", "bbb", "sss", "ccc"));
lots.add(new Lot(1, "bbb", "ccc", "bbb", "sss", "ccc"));
Collections.sort(lots);
}
}
Create Lot class :
class Lot implements Comparable<Lot> {
public int lotNumber;
public String firstName;
public String lastName;
public String price;
public String squareFeet;
public String noOfBedRooms;
public Lot(int lotNumber, String firstName, String lastName, String price, String squareFeet, String noOfBedRooms) {
this.lotNumber = lotNumber;
this.firstName = firstName;
this.lastName = lastName;
this.price = price;
this.squareFeet = squareFeet;
this.noOfBedRooms = noOfBedRooms;
}
public int getLotNumber() {
return lotNumber;
}
public void setLotNumber(int lotNumber) {
this.lotNumber = lotNumber;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getSquareFeet() {
return squareFeet;
}
public void setSquareFeet(String squareFeet) {
this.squareFeet = squareFeet;
}
public String getNoOfBedRooms() {
return noOfBedRooms;
}
public void setNoOfBedRooms(String noOfBedRooms) {
this.noOfBedRooms = noOfBedRooms;
}
#Override
public int compareTo(Lot lot) {
return this.getLotNumber() - lot.getLotNumber();
}
}
Change type of the attributes as you wish.
After the post I realized this is same answer as #Aalekh :)

there is a lot of sorting method that you can implement such as heap sort and bubble sort then you can implement substring in order to reorganize your data :d
for example you can user heap sort , `public static void BubbleSort( int [ ] num )
{
int j;
boolean flag = true; // set flag to true to begin first pass
int temp; //holding variable
while ( flag )
{
flag= false; //set flag to false awaiting a possible swap
for( j=0; j < num.length -1; j++ )
{
if ( num[ j ] < num[j+1] ) // change to > for ascending sort
{
temp = num[ j ]; //swap elements
num[ j ] = num[ j+1 ];
num[ j+1 ] = temp;
flag = true; //shows a swap occurred
}
}
}
}
`
it will take parameters (numbers) sort them and then you use substring ;)

Related

How do I leverage a json mapping file to convert from one pojo to another pojo?

I have two POJOs (Person.java and User.java) that contain similar information. See below:
public class Person {
private String first_name;
private String last_name;
private Integer age;
private Integer weight;
private Integer height;
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getWeight() {
return weight;
}
public void setWeight(Integer weight) {
this.weight = weight;
}
public Integer getHeight() {
return height;
}
public void setHeight(Integer height) {
this.height = height;
}
}
public class User {
private String name_first;
private String name_last;
private Integer my_age;
private Integer my_weight;
private String social_security;
public String getName_first() {
return name_first;
}
public void setName_first(String name_first) {
this.name_first = name_first;
}
public String getName_last() {
return name_last;
}
public void setName_last(String name_last) {
this.name_last = name_last;
}
public Integer getMy_age() {
return my_age;
}
public void setMy_age(Integer my_age) {
this.my_age = my_age;
}
public Integer getMy_weight() {
return my_weight;
}
public void setMy_weight(Integer my_weight) {
this.my_weight = my_weight;
}
public String getSocial_security() {
return social_security;
}
public void setSocial_security(String social_security) {
this.social_security = social_security;
}
}
I have defined a mapping.json file as shown below using GSON.
{
"columnMap": [
{
"userColumn": "name_first",
"personColumn": "first_name"
},
{
"userColumn": "last_first",
"personColumn": "first_last"
},
{
"userColumn": "my_age",
"personColumn": "age"
},
{
"userColumn": "my_weight",
"personColumn": "weight"
}
]
}
public class Mapping {
private ArrayList<Pair> columnMap;
public Mapping(){
columnMap = new ArrayList<>();
}
public ArrayList<Pair> getColumnMap() {
return columnMap;
}
public void setColumnMap(ArrayList<Pair> columnMap) {
this.columnMap = columnMap;
}
}
I am writing a utility class helper function that converts between a Person and User object the mapped pairs.
public class Pair {
private String userColumn;
private String personColumn;
public String getUserColumn() {
return userColumn;
}
public void setUserColumn(String userColumn) {
this.userColumn = userColumn;
}
public String getPersonColumn() {
return personColumn;
}
public void setPersonColumn(String personColumn) {
this.personColumn = personColumn;
}
public static void main(String args[]){
}
}
My question is below:
As you can see the returnVal object is being set by me (the programmer) to convert from a User POJO to a Person POJO. How do I leverage the pre-defined mapping.json to do this? The reason I am asking is in the future, the mapping.json file may change (maybe the weight mapping no longer exists). So I am trying to avoid re-programming this Utility.userToPerson() function. How can I achieve this? I am thinking Java reflection is the way to go, but I would like to hear back from the Java community.
public class Utility {
public static Person userToPerson(User u){
Person returnVal = new Person();
returnVal.setAge(u.getMy_age()); // <-- Question How do I leverage mapping.json here?
returnVal.setFirst_name(u.getName_first());
returnVal.setLast_name(u.getName_last());
returnVal.setWeight(u.getMy_weight());
return returnVal;
}
}
You can introspect the beans (i.e. User and Person) for the field names and call corresponding getter from User to fetch the value. Later call corresponding setter in Person.
Here I have taken userToPersonFieldsMap for mapping the field, you can load mapping from JSON file and construct the map accordingly.
Important code section is the for loop, where it dynamically calls getter and setter and does the job.
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
public class UserToPersonMapper {
public static void main(String[] args) throws IntrospectionException, InvocationTargetException, IllegalAccessException {
Map<String, String> userToPersonFieldsMap = new HashMap<>();
userToPersonFieldsMap.put("name_first", "first_name");
userToPersonFieldsMap.put("last_first", "first_last");
userToPersonFieldsMap.put("age", "personAge");
//existing user
User user = new User("Tony", "Stark", 20);
//new person - to be initialised with values from user
Person person = new Person();
for (Map.Entry<String, String> entry : userToPersonFieldsMap.entrySet()) {
Object userVal = new PropertyDescriptor(entry.getKey(), User.class).getReadMethod().invoke(user);
new PropertyDescriptor(entry.getValue(), Person.class).getWriteMethod().invoke(person, userVal);
}
System.out.println(user);
System.out.println(person);
}
}
class User {
private String name_first;
private String last_first;
private int age;
public User(String name_first, String last_first, int age) {
this.name_first = name_first;
this.last_first = last_first;
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName_first() {
return name_first;
}
public String getLast_first() {
return last_first;
}
public void setName_first(String name_first) {
this.name_first = name_first;
}
public void setLast_first(String last_first) {
this.last_first = last_first;
}
#Override
public String toString() {
return "User{" +
"name_first='" + name_first + '\'' +
", last_first='" + last_first + '\'' +
", age=" + age +
'}';
}
}
class Person {
private String first_name;
private String first_last;
private int personAge;
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public void setFirst_last(String first_last) {
this.first_last = first_last;
}
public String getFirst_name() {
return first_name;
}
public String getFirst_last() {
return first_last;
}
public int getPersonAge() {
return personAge;
}
public void setPersonAge(int personAge) {
this.personAge = personAge;
}
#Override
public String toString() {
return "Person{" +
"first_name='" + first_name + '\'' +
", first_last='" + first_last + '\'' +
", personAge=" + personAge +
'}';
}
}
You can tweak and try it out this example to make it more align with your requirement.
Note:
This solution uses reflection.

Java Store multiple phone number for one user

Question: Store more than 1 user data with id, name, weight, age, and phone number (can have multiple phone number)
How do I store multiple phone number for one user?
I facing an error "Exception in thread "main" java.lang.NullPointerException at Store_User.main(Store_User.java:29). Anyone can solve it?
import java.util.List;
public class User {
private int usrid;
private String name;
private double weight;
private int age;
private List<String> Pnum;
public User(int usrid, String name, double weight, int age, List<String> Pnum){
this.usrid = usrid;
this.name = name;
this.weight = weight;
this.age = age;
}
public void setUsrid(int usrid) {
this.usrid = usrid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public List<String> getPnum() {
return Pnum;
}
public void setPnum(List<String> pnum) {
Pnum = pnum;
}
int getUID(){
return usrid;
}
}
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
public class Store_User {
public static void main(String[] args) {
User usr1 = new User(1,"Mark", 55.5, 26, Arrays.asList("0140392812", "0123456789"));
User usr2 = new User(2, "Ken", 54.7, 33, Arrays.asList("0129876543"));
User usr3 = new User(3, "Callie", 62.3, 34, Arrays.asList("06123456", "0987654322", "01798654321"));
ArrayList<User> ulist = new ArrayList<User>();
ulist.add(usr1);
ulist.add(usr2);
ulist.add(usr3);
Iterator itr=ulist.iterator();
while(itr.hasNext()){
User usr = (User)itr.next();
System.out.println(usr.getUID() +", " + usr.getName() +", " + usr.getAge() +", " + usr.getWeight());
String out ="";
for(String number: usr.getPnum()){
out += number + ";";
}
System.out.println(out);
}
}
}
Chat conversation end
EDIT: Phone numbers are stored as an ArrayList of Strings and are "linked" to the usrId since they are non-static members of the same class, hence each User object will have it's own id and list of numbers. You can access the phone numbers of a user using:
usr.getPnum()
where usr is an instance of User.java, this will return a ArrayList<String> representing the phone numbers, if you want a specific number you can access the list by index like so:
usr.getPnum().get(0) //The index in this case is 0
User.java
import java.util.List;
public class User {
private int usrid;
private String name;
private double weight;
private int age;
private List<String> Pnum;
public User(int usrid, String name, double weight, int age, List<String> Pnum){
this.usrid = usrid;
this.name = name;
this.weight = weight;
this.age = age;
this.Pnum = Pnum;
}
public void setUsrid(int usrid) {
this.usrid = usrid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public List<String> getPnum() {
return Pnum;
}
public void setPnum(List<String> pnum) {
Pnum = pnum;
}
int getUID(){
return usrid;
}
}
Store_User.java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
public class Store_User {
public static void main(String[] args) {
User usr1 = new User(1,"Tee Ting Ong", 55.5, 26, Arrays.asList("00000000", "00000000", "00000000"));
User usr2 = new User(2, "Tee Soon Teh", 54.7, 33, Arrays.asList("00000000", "00000000"));
User usr3 = new User(3, "Tee Ting Ken", 62.3, 34, Arrays.asList("00000000"));
ArrayList<User> ulist = new ArrayList<User>();
ulist.add(usr1);
ulist.add(usr2);
ulist.add(usr3);
Iterator itr=ulist.iterator();
while(itr.hasNext()){
User usr = (User)itr.next();
System.out.println(usr.getUID() +", " + usr.getName() +", " + usr.getAge() +", " + usr.getWeight());
//This print out the numbers
String out = "";
for(String number : usr.getPnum()){
out += number + ";";
}
System.out.println(out);
}
}
}

Adding Items to my inventory in Java

I am making a text-based game on JavaFX, and after I hit a tree, I want to get Oak logs.
I have already built my inventory, and I have put default items in it such as Water, Bread, etc.
I am trying to add my Oak Logs to my inventory, but nothing is working.
Here is a part of my code:
Item ItemList[] = {new Bread(), new OakLog()};
Optional<ButtonType> result = alert.showAndWait();
if(result.get() == buttonTypeOak) {
woodcuttingXP = woodcuttingXP + oakXP;
dialogue.appendText("You swing at an Oak tree. + " + oakXP + "XP.\n");
dialogue.appendText("You gathered 1 log.\n");
mainCharacter.getInventory().add(new OakLog());
}
Here is my Item Class:
package game;
public class Item {
private String name;
private int weight;
private int quantity;
private int value;
private String description;
public Item(String name, int value, String description) {
this.name = name;
this.value = value;
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String toString() {
return getName();
}
}
And finally, here is my Character class:
package game;
import java.util.ArrayList;
import beverages.Water;
import items.OakLog;
import rawFood.Bread;
public class Character {
private String name;
private int hydrationLevel;
private int healthLevel;
private int hungerLevel;
private int woodcuttingLevel;
public int getWoodcuttingLevel() {
return woodcuttingLevel;
}
public void setWoodcuttingLevel(int woodcuttingLevel) {
this.woodcuttingLevel = woodcuttingLevel;
}
public int getHungerLevel() {
return hungerLevel;
}
public void setHungerLevel(int hungerLevel) {
this.hungerLevel = hungerLevel;
}
private ArrayList<Item> inventory = new ArrayList<Item>();
public ArrayList<Item> getInventory() {
return inventory;
}
public void setInventory(ArrayList<Item> inventory) {
this.inventory = inventory;
}
//creates a person with two basic items
public Character(String name){
this.name = name;
this.hydrationLevel = 100;
this.healthLevel = 100;
this.hungerLevel = 100;
this.woodcuttingLevel = 1;
addToInventory (new Bread());
addToInventory (new OakLog());
addToInventory (new Water());
}
//GETTERS AND SETTERS
public String getName() {
return name;
}
public int getHydrationLevel() {
return hydrationLevel;
}
public void setHydrationLevel(int hydrationLevel) {
this.hydrationLevel = hydrationLevel;
}
public int getHealthLevel() {
return healthLevel;
}
public void setHealthLevel(int healthLevel) {
this.healthLevel = healthLevel;
}
//END GETTERS AND SETTERS
/*Method Name: eat()
*Method Inputs: a piece of food
*Method Purpose: Will allow the user to eat food
*/
public Item getItemFromInventory(int index){
Item item = inventory.get(index);
return item;
}
public void addToInventory(Item item){
if(inventory.contains(item)){
item.setQuantity(item.getQuantity()+1);
}
else{
item.setQuantity(1);
inventory.add(item);
}
}
public String toString(){
return "Character Stats:\nName:" + getName() + "\nHydration: " + getHydrationLevel() + "\nHealth: " + getHealthLevel() + "\nWoodcutting: " + getWoodcuttingLevel();
}
}
In your code, you have:
if(inventory.contains(item)){
item.setQuantity(item.getQuantity()+1);
}
This just updates the quantity of the local variable item in the method, not the item in the inventory.

Example of ClassName.method1Name().method2Name();

Hi any one give me example of ClassName.method1Name().method2Name() what is this please give me simple java program example of this.I am confusing of this code.
ClassName.get1().get2().get3() is just a chain of method calls on successive classes. Imagine 3 objects:
class ClassName {
public static o1 get1() {
return new o1();
}
}
class o1 {
public o2 get2() {
return new o2();
}
}
class o2 {
public o3 method3() {
return new o3();
}
}
In each instance, the function call returned another object, which itself had a method to call, and so on and so forth.
Return current object reference from method call using return this;
public class ReturnClassType {
private String firstname;
private String lastname;
public ReturnClassType firstName(String firstname){
this.firstname = firstname;
return this;
}
public ReturnClassType lastName(String lastname){
this.lastname = lastname;
return this;
}
public String getName(){
return firstname + " " + lastname;
}
public static void main(String[] args) {
String Name = new ReturnClassType().firstName("Vicky").lastName("Thakor").getName();
System.out.println(Name);
}
}
Class Employee{
public Static List<Employee> list=new ArrayList<Employee>();
private String name;
Employee(){
public Employee(){
name = "";
}
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
}
public static void main(String [] args){
Employee e = new Employee();
e.setname("test");
Employee e2 = new Employee();
e2.setname("test2");
Employee.list.add(e);
Employee.list.add(e2);
for(int i = 0 ; i < Employee.list.size(); i++){
System.out.println(Employee.list.get(i).getName());
}
}

My toString() is returning only one object times the number of the total object

Can someone help solving this. I want to print all the object once please
public class Student {
private static String firstName;
private static String lastName;
private static int studentId;
private static String major;
private static double balance;
public Student (String fName, String lName,int id,String mjr,double blce) {
firstName = new String(fName);
lastName = new String(lName);
studentId = id;
major = new String(mjr);
balance = blce;
}
public String toString () {
return firstName + "\t" + lastName + "\t" + studentId + "\t" + major + "\t$" + balance;
}
public boolean equals (Object obj) {
if (obj instanceof Student) {
Student collegeStud = (Student) obj;
return (this.firstName.equals(collegeStud.firstName));
} else
return false;
}
public static String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public static String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public static int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public static String getMajor() {
return major;
}
public void setMajor(String major) {
this.major = major;
}
public static double getBalance() {
return balance;
}
/*
* .commmm
*/
public void setBalance(double balance) {
this.balance = balance;
}
public static void main (String[] args) {
Student Mike = new Student ("Mike","Versace", 99, "CS",0.00);
Student John = new Student ("John","Sling" ,97, "Maths", 20.00);
Student Bob = new Student ("Bob","Tomson" ,57, "Physic",5.00);
System.out.println (Mike.toString() + "\n" + John.toString());
if (Mike.equals(John))
System.out.println ("Mike is John");
else
System.out.println ("Mike is NOT John");
}
}
import java.io.ObjectInputStream.GetField;
public class StudentList {
private int numberOfStudents=0;
private Student[] studentListArray;
//private int studentCount = 0;
StudentList () {
numberOfStudents=0;
studentListArray = new Student[100];
}
public void createStudent(String firstName, String lastName,int studentId, String major, double balance){
Student collegeStud = new Student(firstName, lastName, studentId, major, balance);
addStudent(collegeStud);
numberOfStudents++;
}
public void addStudent (Student collegeStud) {
studentListArray[numberOfStudents++]=new Student(collegeStud.getFirstName(), collegeStud.getLastName(),
collegeStud.getStudentId(), collegeStud.getMajor(),collegeStud.getBalance());
}
public String toString() {
String result = "";
for (int i=0; i<numberOfStudents; i++) {
result += studentListArray[i].toString() + "\n";
}
return result;
}
public Student[] getList() {
return studentListArray;
}
public int listSize() {
return numberOfStudents;
}
public Student searchForStudent (String firstName){
int index = 0;
while (index < numberOfStudents) {
if (studentListArray[index].equals(new Student(Student.getFirstName(),Student.getLastName(),Student.getStudentId(),Student.getMajor(),Student.getBalance()))) {
return studentListArray[index];
}
index++;
}
return null;
}
public static void main(String args[]) {
StudentList theList = new StudentList();
theList.addStudent (new Student ("John","Sling" ,97, "Maths", 20.00));
theList.addStudent (new Student ("Mike","Versace", 99, "CS",0.00));
theList.addStudent (new Student ("Bob","Tomson" ,57, "Physic",5.00));
//theList.createStudent(new Student(Student.getFirstName(),Student.getLastName(),Student.getStudentId(),Student.getMajor(),Student.getBalance()));
//theList.searchForStudent(new String());
System.out.println (theList.toString());
}
}
The problem is that you marked your fields as static. Remove it and the method will work as expected.
public class Student {
//non-static fields
private String firstName;
private String lastName;
private int studentId;
private String major;
private double balance;
//similar for getters, setters and toString method
}
Static members are shared amongst all objects in a class rather than being one per object. Hence each new object you create is overwriting the data of the previous one.
More info:
What does the 'static' keyword do in a class?

Categories