Sort Array of Objects by Objects' Property [duplicate] - java

This question already has answers here:
How do I use Comparator to define a custom sort order?
(9 answers)
Closed 9 years ago.
I know there are a lot of questions like this, and I have been reading a lot but I really can't figure it out. I have a user defined object, Team, which has the properties team name (String), batAvg (Double) and slugAvg (Double). I want to arrange, and print the teams in order of descending batAvg, then in order of descending slugAvg. I have an array of all the teams, teamArray (Team[]). What is the best way to go about sorting this array by the teams batting and slugging average. I've tried a bunch of stuff, but none of it seems to work.

Pls check the following code,
import java.util.Arrays;
import java.util.Comparator;
public class Team {
private String name;
private double batAvg;
private double slugAvg;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getBatAvg() {
return batAvg;
}
public void setBatAvg(double batAvg) {
this.batAvg = batAvg;
}
public double getSlugAvg() {
return slugAvg;
}
public void setSlugAvg(double slugAvg) {
this.slugAvg = slugAvg;
}
public static void main(String[] argv){
Team[] teams = new Team[2]; //TODO, for testing..
Arrays.sort(teams, new TeamComparator()); //This line will sort the array teams
}
}
class TeamComparator implements Comparator<Team>{
#Override
public int compare(Team o1, Team o2) {
if (o1.getSlugAvg()==o2.getSlugAvg()){
return 0;
}
return o1.getSlugAvg()>o2.getSlugAvg()?-1:1;
}
}

Related

How to convert an UML class with a constructor to a java object?

I am trying to make a constructor that creates an array of empty homework scores (6 per student) and an array of empty exam scores (3 per student).
The getHomeworkAverage() method returns the average score on the student’s homework. The getFinalScore() method returns the final grade for each student using the grading as follows: (15% for exam1, 25% for exam2, 30% for exam3, and 30% for the homework average).
UML Diagram Here
public class Student {
private String name;
private int[] homeworks;
private int[] exams;
private int[] homeworkScores;
private int[] examScores;
private double homeworkAvergae;
private int finalScore;
public Student(String name, int[] homeworks, int[] exams, int[] homeworkScores, int[] examScores, double homeworkAvergae, int finalScore) {
this.name = name;
this.homeworks = homeworks;
this.exams = exams;
this.homeworkScores = homeworkScores;
this.examScores = examScores;
this.homeworkAvergae = homeworkAvergae;
this.finalScore = finalScore;
}
public int[] getHomeworkScores() {
return homeworkScores;
}
public void setHomeworkScores(int[] homeworkScores) {
this.homeworkScores = homeworkScores;
}
public double getHomeworkAvergae() {
return homeworkAvergae;
}
public int[] getExamScores() {
return examScores;
}
public void setExamScores(int[] examScores) {
this.examScores = examScores;
}
public int getFinalScore() {
return finalScore;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int[] getHomeworks() {
return homeworks;
}
public void setHomeworks(int[] homeworks) {
this.homeworks = homeworks;
}
public int[] getExams() {
return exams;
}
public void setExams(int[] exams) {
this.exams = exams;
}
}
Is there a constructor in the diagram?
If taken by the book, your UML class does not contain any constructor. A constructor in UML would be an operation with the stereotype «Create» and returning a Student:
+ «Create» Student(name:String):Student
Of course, several mainstream OOP languages use the convention of a constructor named like the class and with no return type specified. This is why many people would understand Student(name:String) as being the constructor, despite the UML inconsistency.
What is the constructor signature in the diagram?
Assuming that Student(name:String), you would need to implement this class as foreseen in the design:
public class Student {
...
public Student(String name) {
...
}
}
Other remarks
If you have difficulties with initialising arrays, you may find plenty of answers on SO. My first guess would be something like:
homeworks = new int[6];
...
I will not review the code nor complete missing parts. The only thing that I'd like to highlight is that the getters for array fields return the reference to the object's array, which allow to update the content of the array without control. Similarly, setting the array, reuses another array and does not overwrite the current array content. Look here on SO how to clone arrays for avoiding these risks
Your question is how to structure the constructor ?
int[] homeworks = new int[]{ 1,2,3,4,5,6,7,8,9,10 };
int[] exams = new int[]{ 1,2,3,4,5,6,7,8,9,10 };
int[] homeworkScores = new int[]{ 1,2,3,4,5,6,7,8,9,10 };
int[] examScores = new int[]{ 1,2,3,4,5,6,7,8,9,10 };
Student student = new Student(
"Name",
homeworks,
exams,
homeworkScores,
examScores,
6.0,
6
);

String alphabetical order using List or Arraylist [duplicate]

This question already has answers here:
How to sort List of objects by some property
(17 answers)
Closed 3 years ago.
In this program I sorted strings in Alphabetic way in Simple Array but how can I do the same thing using List or ArrayList, Suppose I have a class Students and I want to order names in an alphabetically way, so how can I do that?
public class CityData{
public static String citynames[]= {"Hyderabad","Karachi","Abtabad","AzadKashmir"};
public static void main(String args[]) {
int size=citynames.length;
String temp=null;
for(int i=0; i<size; i++) {
for(int j=i+1; j<size; j++) {
if(citynames[i].compareTo(citynames[j])>0) {
temp=citynames[i];
citynames[i]=citynames[j];
citynames[j]=temp; }
}
System.out.println(citynames[i]);
}
}
}
Result:
Abtabad
AzadKashmir
Hyderabad
Karachi
You can sort the collections based on your requirements.
If the input objects for collections is implementing the Comparable interface like String, Integer, Double classes, then you can directly use Collections.sort() method from Collections util class
List<String> al = new ArrayList<>();
al.add("Hyderabad");
al.add("Karachi");
al.add("Abtabad");
al.add("AzadKashmir");
al.add("Udupi");
al.add("Jammu");
Collections.sort(al);
Or you can sort the list based on your requirement.(Reverse alphabetical Order)
Collections.sort(al, (str1, str2) -> str2.compareTo(str1));
If you don't want to use the Collections class, then directly use the sort() method present in List interface.
i. Albhabetical Order
al.sort((str1, str2) -> str1.compareTo(str1));
ii. Reverse Albhabetical Order
al.sort((str1, str2) -> str2.compareTo(str1));
The above solution is for the Objects where the class implements the Comparable Interface like String, Integer, Double, etc...
When to sort the Custom Classes, you need to implement sort by Comparator class or Lambda expression for the Comparator.
Consider you have a Student Class, and need to sort by city names. You can use below code.
Student Class
public class Student {
private String name;
private String city;
public Student() {}
public Student(String name, String city) {
this.name = name;
this.city = city;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
#Override
public String toString() {
return "Student -> [name=" + name + ", city=" + city + "]";
}
}
Sorting By Collection Class sort() method
Student st1 = new Student("Samir", "Hyderabad");
Student st2 = new Student("Akbar", "Karachi");
Student st3 = new Student("Ramu", "Abtabad");
Student st4 = new Student("Rahim", "AzadKashmir");
Student st5 = new Student("Sardar", "Udupi");
Student st6 = new Student("Fahad khan", "Jammu");
List<Student> al2 = new ArrayList<>();
al2.add(st1);
al2.add(st2);
al2.add(st3);
al2.add(st4);
al2.add(st5);
al2.add(st6);
//Alphabetical Order
Collections.sort(al2, (std1, std2) -> std1.getCity().compareTo(std2.getCity()));
//Reverse Alphabetical Order
Collections.sort(al2, (std1, std2) -> std2.getCity().compareTo(std1.getCity()));
By using List.sort() method
//Alphabetical Order
al2.sort((std1, std2) -> std1.getCity().compareTo(std2.getCity()));
//Reverse Alphabetical Order
al2.sort((std1, std2) -> std1.getCity().compareTo(std2.getCity()));
What you are looking for is actually pretty simple to do:
Instead of using citynames[i] or citynames[j], for Lists and ArrayLists, you use citynames.get(i) or citynames.get(j).
Just think of List.get() is the same as the brackets you put before for the simple arrays.
Just remember, when you want to set a value, you actually have to use the List.set(int index, Object value).
The same can be said if you are trying to get the length of the List or ArrayList. You can simply replace citynames.length to citynames.size();
public static void main(String args[]) {
int size=citynames.size();
String temp=null;
for(int i=0; i<size; i++) {
for(int j=i+1; j<size; j++) {
if(citynames.get(i).compareTo(citynames.get(j))>0) {
temp=citynames.get(i);
citynames.set(i, citynames.get(j));
citynames.set(j, temp); }
}
System.out.println(citynames.get(i));
}
}
Update: Better Solution:
Note: When using Collections.sort() it is important to make sure the object type of the array implements Comparable. the Collections.sort() uses the compareTo() within the object class to sort the elements.
public class Main(){
import java.util.Collections;
public static void main(String args[]) {
ArrayList<City> citynames = new ArrayList<City>();
citynames.add("Hyderabad");
citynames.add("Karachi");
citynames.add("Abtabad");
citynames.add("AzadKashmir");
Collections.sort(citynames);
for(cityname : citynames)
System.out.println(cityname);
}
}
public class City implements Comparable{
private String name;
// Constructor
public City(String name){
this.name = name;
}
// Getter method
public String getName(){
return name;
}
// compareTo Method
public int compareTo(City other){
return name.compareTo(other.getName());
}
// Other methods may exist
}
For more information: https://docs.oracle.com/javase/tutorial/collections/interfaces/order.html
I do not have the rights to comment yet, hence adding at as an answer.
You can google this easily and also lookup API for sorting collections.
Code in java 8
public class ArrayListSort {
public static String citynames[] = { "Hyderabad", "Karachi", "Abtabad", "AzadKashmir" };
public static void main(String args[]) {
Student stud1 = new Student("Alex", 20);
Student stud2 = new Student("Bryan", 21);
Student stud3 = new Student("Chris", 22);
Student stud4 = new Student("Dan", 23);
List<Student> students = new ArrayList<>(Arrays.asList(stud4, stud3, stud2, stud1));
Collections.sort(students);
for(Student stud: students){
System.out.println(stud.getName());
}
}
}
class Student implements Comparable<Student> {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return this.name;
}
public int getAge() {
return age;
}
#Override
public int compareTo(Student other) {
return this.name.compareTo(other.name);
}
}
Edit 1 to answer your comment, look up Comparable interface

Cannot identify Error reasoning - Related to ArrayList and FOR loops, how could I fix my code? [duplicate]

This question already has answers here:
Remove elements from collection while iterating
(9 answers)
Closed 3 years ago.
I am creating a very simple simple Bank Manager Class which handles a number of Bank Account objects - each object is created with a unique accountNumber, accName, etc., This is how a bank account is created:
package banksystem;
import java.util.*;
public class BankAcc {
private String accountName;
private int accountNumber;
private int accountOverdraft;
private int currentBalance;
public BankAcc(String accountName, int accountNumber,
int accountOverdraft, int currentBalance){
this.accountName = accountName;
this.accountNumber = accountNumber;
this.accountOverdraft = accountOverdraft;
this.currentBalance = currentBalance;
}
public void deposit(int money){this.currentBalance += money;}
public void withdraw(int money){
int curr = this.currentBalance + this.accountOverdraft;
if (money < curr){this.currentBalance -= money;}
}
public String accountName(){return this.accountName;}
public int accountNumber(){return this.accountNumber;}
public int getCurrentBalance(){return this.currentBalance;}
public int accountOverdraft(){return this.accountOverdraft;}
}
The bank account Manager class is created as below, I am using for loops so that the program can identify Bank Accounts I want to edit.
package banksystem;
import java.util.*;
public class BankMngr {
private ArrayList<BankAcc> bankAccounts = new ArrayList<>();
public BankMngr(){
this.bankAccounts = new ArrayList<BankAcc>();
}
public void addBankAcc(String accountName, int accountNumber, int
accountOverdraft, int currentBalance){
BankAcc newBankAcc = new BankAcc(accountName, accountNumber,
accountOverdraft, currentBalance);
bankAccounts.add(newBankAcc);
}
public void removeBankAcc(int accountNumber){
for(BankAcc b: bankAccounts){
if (b.accountNumber() == accountNumber){bankAccounts.remove(b);}
else;
}
}
public String accountsList(){
String s = "ACCOUNTS UNDER MANAGER:" + "\n";
for(BankAcc b: bankAccounts){s+= b.accountNumber()+ " " +
b.accountName() + "\n";}
return s;
}
}
All seems to work fine, but when I use this code in my main, I get an error.
package banksystem;
import java.util.*;
public class BankSystem{
public static void main(String[] args) {
BankMngr ManagerBob = new BankMngr();
ManagerBob.addBankAcc("John", 1425, 2000, 1000);
ManagerBob.addBankAcc("Kane", 1358, 4000, 6000);
ManagerBob.addBankAcc("Kane", 1693, 4000, 6000);
ManagerBob.addBankAcc("Dave", 1976, 2000, 3500);
System.out.println(ManagerBob.accountsList());
ManagerBob.removeBankAcc(1976);
System.out.println(ManagerBob.accountsList());
}
}
I just want to remove the account 1976 but get an error. I can't figure out what the solution may be, and the error message doesn't help me as I'm quite a beginner, I'd really appreciate a point in the right direction,
thanks guys.
I'm assuming the error you're getting is the ConcurrentModificationException. You shouldn't remove from a list when browsing it with a "for each" loop.
See:
ConcurrentModificationException for ArrayList

Sorting of Arraylist of Custom Object in java [duplicate]

This question already has answers here:
Sort ArrayList of custom Objects by property
(29 answers)
Closed 5 years ago.
I have a Custom Object Suppose Team
public class Team{
String name;
int teamNo;
ArrayList<Team> innerTeams;
int teamId;
//Getters and Setter Methods
Now I want to Sort it in Ascending Order of First Property name taking into account that each Team Object has a property of itself as Team as arraylist declared as innerTeams How can I be able to Sort this. So utlimately when any arrayList of object Team is present it should be sorted.
Please anyone help me with this.
The easiest way is to have your Team class implement Comparable. You can tweak the logic inside of the compareTo to match your needs, e.g. compare inner team names, etc. Then you use Collections.sort() to do the actual sorting.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Team implements Comparable<Team> {
String name;
int teamNo;
List<Team> innerTeams = new ArrayList<>();
int teamId;
#Override
public int compareTo(Team o) {
if(o == null) {
return 1;
} else if(name == null) {
return 0;
} else {
return name.compareTo(o.name);
}
}
public static void main(String[] args) {
Team team1 = new Team();
team1.name = "z";
Team team2 = new Team();
team2.name = "a";
List<Team> teams = new ArrayList<>();
teams.add(team1);
teams.add(team2);
System.out.println(teams);
Collections.sort(teams);
System.out.println(teams);
}
#Override
public String toString() {
return name;
}
}
Output:
[z, a]
[a, z]
You can then also use the same approach to sort innerTeams by name if needed.
You should define Comparator of Team.
class TeamComparator implements Comparator<Team>{
public int compare(Team o1,Team o2){
return o1.name.compareTo(o2.name);
}
}
And sort by Collections.sort(teamList, new TeamComparator())

About sorting array list

I am trying to ensure that the objects i insert in productDatabase have not been already inserted and that i sort my arraylist using method sortData but without using any comparators in method sortData
public class Application {
public static void main(String[] args) {
Product p = new Product(15,"test",3.45);
Product p2 = new Product(15,"test",3.45);
Product p3 = new Product(4716,"koukouroukou",1.25);
Product p4 = new Product(6002,"bananofatsoula",0.60);
ProductDatabase productDatabase = new ProductDatabase();
productDatabase.addProduct(p);
productDatabase.addProduct(p2);
productDatabase.addProduct(p3);
productDatabase.addProduct(p4);
productDatabase.printDatabase();
productDatabase.sortDatabase();
productDatabase.printDatabase();
}
public class Product {
private int code;
private String name;
private double price;
public Product(int code, String name, double price){
this.code = code;
this.name = name;
this.price = price;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String toString(){
return code+" , description: "+name+", price: "+price;
}
public int hashCode(){
return 31 * code + name.hashCode();
}
public boolean equals(Object o){
Product other = (Product)o;
if (this.code == other.code){
return true;
}
else{
return false;
}
}
import java.util.ArrayList;
import java.util.Collection;
public class ProductDatabase {
private ArrayList<Product> productDatabase;
public ProductDatabase(){
productDatabase = new ArrayList<Product>();
}
public void addProduct(Product p){
if(!productDatabase.contains(p)){
productDatabase.add(p);
}
}
public void printDatabase(){
for(Product product : productDatabase){
System.out.println(product);
}
}
public void sortDatabase(){
// ????????????????????????????????????????????????????????????
So my questions are
Does contain(p) is enough to ensure that the same product is not already in the list?
products are the same when they have the same code and name.if not what i have to do?
How i sort my withous using comparators in class ProductDatabase.maybe by a new method in product ?
Does productDatabase extends Product???
You can return bool value in order to know the product is already there or not . Code is used to ensure the differentiation of products if not add another code id.
Product instance will carry information of just one Product so Sort must be done in the member function of class having all the records of product, not just one.
No product_database does not extend product . It is a log of product class not a part .
your questions 1 and 2 are a little unclear. Can you re-write them? As for question 3. No ProductDatabase does not extend product, neither should it. ProductDatabase HAS products. ProductDatabase is not a product
Yes, contains() is enough (in our case) to ensure uniqueness
Since you implemented equals and hashCode - you're good
You don't need to sort if you don't have another purpose to do so, but since you're using an ArrayList every time contains() is called it iterates the whole list which is not very efficient. A better implementation would use Set (a HashSet for example)
ProductDatabase does not have to extend Product - it contains a list/set of products but it doesn't have any character/behavior like Product
Yes, contain(p) is enough to ensure that the same product is not already in the list, because you overrided "equals" method.
In "equals" you can use shorter construction:
Product other = (Product)o;
return this.code == other.code;
For sort ArrayList with java.util.Collections class two options possible:
Collections.sort(List list, Comparator c). You have to write own Comparator class and pass as second parameter.
Collections.sort(List list) and class Product must implement Comparable interface
Yes, Contain(p) is enough to ensure that the same product is not already in the list BUT that is NOT efficient. Use a Set instead of ArrayList.
For question 2, you have to decide the when the two products are equal and code that in your equals method like you did for 'product code'

Categories

Resources