sort custom Array List - java

I have a class called x which is a array list and needs to be sorted in Decreasing order by Value.
My Class-
public static class x
{
public int id;
public double value;
public x(int _id, double _value)
{
id = _id;
value = _value;
//System.out.println(Integer.toString(id));
}
public Integer getID(){
return id;
}
public double getValue(){
return value;
}
//Sorting
public static Comparator<x> getComparator(SortParameter... sortParameters) {
return new xComparator(sortParameters);
}
public enum SortParameter {
VAL_DESCENDING
}
private static class xComparator implements Comparator<x> {
private SortParameter[] parameters;
private xComparator(SortParameter[] parameters) {
this.parameters = parameters;
}
public int compare(x o1, x o2) {
int comparison;
for (SortParameter parameter : parameters) {
switch (parameter) {
case VAL_DESCENDING:
comparison = o2.id - o1.id;
if (comparison != 0) return comparison;
break;
}
}
return 0;
}
}
}
I Call it like:
cp = x.getComparator(x.SortParameter.VAL_DESCENDING);
Collections.sort(attr1, cp);
attr1 is my array list
Just for Reference I am following this
I am getting error:
cannot find symbol : variable cp
I am a newbie to java :(

try using Comparator<x> cp = x.getComparator(x.SortParameter.VAL_DESCENDING); to declare it. you can not use a variable until it is declared

Related

Sort Java list of objects

I need to sort a java list containing objects of type Hotel
List<Hotel> hotelList = new ArrayList<>();
Inside the class I do have the method
#Override
public List<Room> getAvailableRooms() {
return this.rooms;
}
I need to sort my hotelList by the price attribute found in Room class.
Any suggestions?
You should either use a Comparator or implement the Comparable interface
public class Foo implements Comparable<ToSort> {
private int val;
public Foo(int val){
this.val = val;
}
#Override
public int compareTo(ToSort f) {
if (val > f.val) {
return 1;
}
else if (val < f.val) {
return -1;
}
else {
return 0;
}
}
Read more here
https://dzone.com/articles/sorting-java-arraylist

how to create comparator with generic Treeset?

in need help with generics ,i have this class:
public class Course<T> {
private T idOrName;
private float avg;
public Course(T idOrName,float avg){
this.idOrName=idOrName;
this.avg=avg;
}
}
....and i need to make the user choose between String or Integer and then create a Treeset and sort it by this generics type.how can i do that if i dont know if its a number or String?? i have a problem with making the comparator :
Set<Course<?>> list=new TreeSet<>(new Comparator<Course<?>(){
#Override
public int compare(Course<?> o1, Course<?> o2) {
// TODO Auto-generated method stub
return 0;
}
});
First you need to indicate that the expected class must be Comparable by proceeding as next
public class Course<T extends Comparable<T>> {
...
}
Then your generic comparator could be something like this:
Set<Course<?>> list = new TreeSet<>(new Comparator<Course<?>>(){
#Override
public int compare(Course<?> o1, Course<?> o2) {
// If idOrName are both of the same class then we use the
// comparator of this class as we know that they are Comparable
if (o1.idOrName.getClass() == o2.idOrName.getClass()) {
return ((Comparable)o1.idOrName).compareTo((Comparable)o2.idOrName);
}
// If they are not of the same class we compare the name of the class
return o1.idOrName.getClass().getName().compareTo(
o2.idOrName.getClass().getName()
);
}
});
Go for duplication of the fields. Any other solution would be more circumstantial. Here I added a toString that unifies both cases.
public class Course {
private int id;
private String name;
private float avg;
public Course(int id, float avg){
this(id, "", avg);
}
public Course(String name, float avg){
this(0, name, avg);
}
private Course(int id, String name, float avg){
this.id = id;
this.name = name;
this.avg = avg;
}
#Override
public String toString() {
return id != 0 ? String.value(id) : name;
}
}
And a comparator (since java 8):
Comparator.comparingInt(course -> course.id)
.thenComparing(course -> course.name);
Comparator.comparingInt(Course::getId)
.thenComparing(Course::getName);

Getting enum value by passing preset ordinal

I have looked this link : Convert from enum ordinal to enum type
and tried to get the enum value. But is not working. My enum class is :
public enum OrderStatus {
OPEN(0),
DELIVERED(1),
CANCELLED(3),
PARTIALLY(4)
}
I will pass the values 0,1,3,4 where 2 is missing , so it has no such order. How to get enum by passing 0,1,3 or 4 in groovy or java.
Add a field to the enum, and a constructor:
public enum OrderStatus {
private Integer codice;
public Integer getCodice() {
return codice;
}
private OrderStatus(Integer codice) {
this.codice = codice;
}
OPEN(0),
DELIVERED(1),
CANCELLED(3),
PARTIALLY(4)
}
and then you can define a method like this:
public static OrderStatus getByCodice(int codice) {
for (OrderStatus tipo : values()) {
if (tipo.codice == codice) {
return tipo;
}
}
throw new IllegalArgumentException("Invalid codice: " + codice);
}
Record the value in the enum and build a Map to convert.
public enum OrderStatus {
OPEN(0),
DELIVERED(1),
CANCELLED(3),
PARTIALLY(4);
final int ordinal;
private OrderStatus(int ordinal) {
this.ordinal = ordinal;
}
static Map<Integer, OrderStatus> lookup = null;
public static OrderStatus lookup(int ordinal) {
// Could just run through the array of values but I will us a Map.
if (lookup == null) {
// Late construction - not thread-safe.
lookup = Arrays.stream(OrderStatus.values())
.collect(Collectors.toMap(s -> s.ordinal, s -> s));
}
return lookup.get(ordinal);
}
}
public void test() {
for (int i = 0; i < 5; i++) {
System.out.println(i + " -> " + OrderStatus.lookup(i));
}
}
Just declare a field inside enum as you do in class. And provide a getter method for the field:
public enum OrderStatus
{
OPEN(0),
DELIVERED(1), /*pass value*/
CANCELLED(3),
PARTIALLY(4);
private int value; /*Add a field*/
OrderStatus ( int value )
{
this.value = value;
}
/*Access with getter*/
int getValue ( )
{
return value;
}
}

Add objects to Arraylist and use it outside method

I have a question. I cant solve it and I need some help please. I have an Arraylist of objects then I have a method where objects are created and added to the Arraylist but I want another method where I can print the Arraylist but everytime I try the Arraylist is empty so this is my code:
public class Packages{
ArrayList<Pack> myList = new ArrayList<Pack>();
Pack obj;
public double addPackage(int type, double num){
if(type==1)
{
obj = new Pack(type, num);
total = obj.calculateTotal;
}
else
{
obj = new Pack(type, num);
total = obj.calculateTotal;
}
myList.add(obj);
return total;
}
public int listSize(){
return myList.size();
}
}
Everytime I call the listSize() method it returns 0, looks like when the addPackage method finishes it deletes the objects I added to my Arraylist.
Note: my addPackage method is going to return a double total but at the same time add the objects I create to the arraylist. I need some help please.
I tried your code and it is almost right. I am posting the classes again which I used and which work:
public class Package {
List<Pack> myList = new ArrayList<Pack>();
Pack obj;
double total = 0;
public double addPackage(int type, double num) {
if (type == 1) {
obj = new Pack(type, num);
total = obj.calculateTotal();
} else {
obj = new Pack(type, num);
total = obj.calculateTotal();
}
myList.add(obj);
return total;
}
public int listSize() {
return myList.size();
}
}
Now class Pack is:
public class Pack {
int type;
double value;
public Pack(int type, double value) {
this.type = type;
this.value = value;
}
public double getValue() {
return value;
}
public void setValue(double value) {
this.value = value;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public double calculateTotal() {
return type*value;
}
}
And I verified in this code:
public static void main(String[] args) {
Package pkg = new Package();
pkg.addPackage(10,10);
pkg.addPackage(10,20);
System.out.println(pkg.listSize());
}
And as expected it returns 2. All these classes may not exactly be same as what you have but it will give you the idea about what are you missing.

Is it possible to pass arguments into Enum values?

Suppose I have a Enum defined something like this:
public enum Sample{
// suppose AClass.getValue() returns an int
A(AClass.getValue()),
B(AClass.getValue()),
C(AClass.getValue());
private int _value;
private Sample(int _val){
this._value = _val;
}
public int getVal(){
return _value;
}
I can pull out values using Sample.A or Sample.A.getAVal() without issue.
Now suppose that AClass.getValue() could take a parameter to return a possibly different particular value, eg AClass.getValue(42).
It is possible to pass arguments to a public Enum method and retrive the Enum values? In other words, could I have an Enum definition like
public enum Sample{
// suppose AClass.getValue() returns an int
A(AClass.getAValue()),
B(AClass.getBValue()),
C(AClass.getCValue());
private int _value;
private Sample(int _val){
this._value = _val;
}
public int getVal(){
return _value;
}
public int getVal(int a){
// somehow pull out AClass.getAValue(a)
}
using Sample.A.getValue(42)?
You can do it, but only by making an abstract method in the enum, and overriding it in each value:
public enum Sample {
A(AClass.getAValue()) {
#Override public int getVal(int x) {
return AClass.getAValue(x);
}
},
B(BClass.getAValue()) {
#Override public int getVal(int x) {
return BClass.getBValue(x);
}
},
C(CClass.getAValue()) {
#Override public int getVal(int x) {
return CClass.getCValue(x);
}
};
private int _value;
private Sample(int _val){
this._value = _val;
}
public int getVal(){
return _value;
}
public abstract int getVal(int x);
}
Of course if you could create an instance of some other base type which has a getValue(int x) method, then you could put the code into the enum class itself instead of into the nested ones.
As stated in Java Specification
there is only one instance of each enum constant
So no, you can't have different values of a specific enum constant.
But you could put an array or a map inside your enum, so Sample.A.getValue(42) would return Sample.A.myMap.get(42) :
public enum Sample{
A(),
B(),
C();
Map<Integer, Integer> myMap = new HashMap<Integer, Integer>();
public int getVal(int i){
return myMap.get(i);
}
public int setVal(int i, int v){
return myMap.put(i, v);
}
}
public class App {
public static void main(String[] args) {
Fruit.setCounter(5);
System.out.println(Fruit.Apple.getCmd());
Fruit.setCounter(6);
System.out.println(Fruit.Apple.getCmd());
}
}
public enum Fruit {
Apple {
public String getCmd() {
return counter + " apples";
}
},
Banana {
public String getCmd() {
return counter + " bananas";
}
};
private static int counter = 0;
public abstract String getCmd();
public static void setCounter(int c) {
counter = c;
}
}
Output:
5 apples
6 apples

Categories

Resources