In: Computer Science
I am trying to create a method in JAVA that takes in an ArrayList<Property> and sorts it by the amount of "reviews" that a property has in increasing order. So the most reviews first.
So each listing in the array would contain a different number of reviews, and they should be sorted based on that value.
It does not need to output the values in anyway, but it should return them so they can be output elsewhere.
Please try to use the stub class below. You can edit it obviously.
//Can sort by increasing (true) or decreasing (false)
public ArrayList<Property> sortByNumReviews(boolean
increasing) {
return null;
}
CODE:-
public ArrayList<Property> sortByNumReviews(boolean
increasing) {
ArrayList<Property> arrayList = new
ArrayList<Property>();
int n; // Taking input for number of
properties
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of properties : ");
n = sc.nextInt();
sc.nextLine();
int count=0;
for(int i=0; i<n; i++) // Taking input for number of
reviews for each property
{
System.out.println("Enter number of reviews for Property "+ count+"
: ");
count++;
arrayList.add(sc.nextInt());
sc.nextLine();
}
if(increasing==true) // Sort in increasing
order
{
Collections.sort(arrayList);
}
return arrayList; // Returning sorted
arraylist
}
Explanation:-
In the code input is taken for the number of properties in variable n . Then n times input is taken for the number of reviews for each property and then if increasing is true then the arraylist is sorted using the sort method in Collection class on the basis of number of reviews for each property. Then the sorted arraylist is returned as answer.