Сортировка Comparator по String и int

110
17 марта 2021, 15:10

Нужно, чтобы компаратор отсортировал массив по Типу(Type) и Цене(Price).

package com.company;
import org.omg.PortableServer.POA;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
abstract class Product {
protected Long ean;
protected Double price;
protected String name, type;
public Product (String type,String name, Double price, Long ean) {
    this.name = name;
    this.type = type;
    this.price = price;
    this.ean = ean;
}
public String getType(){
    return type;
}
public String getName() {
    return name;
}
public Double getPrice() {
    return price;
}
public Long getEan() {
    return ean;
}

}

class Food extends Product {

    private int cal;
    private Date creationDate;
    private int expirationTime;
    public Food(String type,String name, Double price, Long ean, int cal, Date creationDate, int expirationTime) {
        super(type,name, price, ean);
        this.cal = cal;
        this.creationDate = creationDate;
        this.expirationTime = expirationTime;
    }
    public String getName() {
        return name;
    }
    public int getCal() {
        return cal;
    }
    public Date getCreationDate() {
        return creationDate;
    }
    public int ExpirationTime() {
        return expirationTime;
    }

    public String toString() {
        return type+": "+name+", "+price+", "+ean+", "+cal+", "+creationDate+", "+expirationTime;
    }
}
class Appliance extends Product{
private int inputPower;
public Appliance(String type,String name, Double price, Long ean, int inputPower) {
    super(type,name, price, ean);
    this.inputPower = inputPower;
}
public String toString() {
    return type+": "+name+", "+price+", "+ean+", "+inputPower;
}
public int getInputPower() {
    return inputPower;
}
}
class Clothes extends Product{
private byte size;
private String material;
public Clothes(String type,String name, Double price, Long ean, byte size, String material) {
    super(type,name, price, ean);
    this.material = material;
    this.size = size;
}
public String toString() {
    return type+": "+name+", "+price+", "+ean+", "+size+", "+material;
}
public byte getSize() {
    return size;
}
public String getMaterial() {
    return material;
}
}
class warehouse {
public static void main(String[] args) throws ParseException {
    Scanner input = new Scanner(System.in);
    SimpleDateFormat Date = new SimpleDateFormat("dd.MM.yyyy");
    ...
    Product[] warehouse = {
            new Food("Food", "Картофель", 5.0, 9031101L, 77, Pt, 12),
            new Food("Food", "Кабачок", 40.0, 9043243L, 17, Ssh, 5),
            new Food("Food", "Шпинат", 12.0, 9054324L, 23, Sp, 6),
            new Food("Food", "Огурец", 9.0, 9045435L, 13, Ct, 8),
            new Food("Food", "Лук", 19.0, 9042353L, 40, On, 165),
            new Appliance("Appliance", "Тостер", 1990.0, 2054355L, 850),
            new Appliance("Appliance", "Холодильник", 15000.0, 2043242L, 2000),
            new Appliance("Appliance", "Блендер", 4299.0, 2033254L, 600),
            // new Appliance("Appliance","Блендер", 4299.0,2033254L,600),
            // new Appliance("Appliance","Блендер", 4299.0,2033254L,600),
            new Clothes("Clothes", "Футболка", 500.0, 3024334L, (byte) 50, "Хлопок"),
            new Clothes("Clothes", "Свитшот", 800.0, 3054332L, (byte) 55, "Полиэстр"),
            new Clothes("Clothes", "Кимоно", 1400.0, 3054345L, (byte) 70, "Хлопок"),
            //new Clothes("Кимоно", 1400.0, 3054345L,(byte)70,"Хлопок"),
            //new Clothes("Кимоно", 1400.0, 3054345L,(byte)70,"Хлопок"),
    };
System.out.println("\nПо цене:");
    Arrays.sort(warehouse, new SortByTypePrice());
    for (Product warehouse1 : warehouse)
        System.out.println(warehouse1.toString());
}

// НЕ УДАЧНЫЙ ПРИМЕР
//static class SortByTypePrice implements Comparator<Product> {
//    public int compare(Product o1, Product o2) {
//        Double prc1 = o1.getPrice();
//        Double prc2 = o2.getPrice();
//        if ((o1.getType().compareTo(o2.getType())) < 0) {
//            return -1;
//        } else if (prc1.compareTo(prc2) > 0) {
//            return 1;
//        } else {
//            return 0;
//        }
//    }
//}
}
Answer 1
Comparator<Product> comparator = Comparator.comparing(Product::getType)
                                           .thenComparing(Product::getPrice);
Arrays.sort(warehouse, comparator);
READ ALSO
Падает deploy через jenkins - ERROR: Exception when publishing, exception message [Exec exit status not zero. Status [1]]

Падает deploy через jenkins - ERROR: Exception when publishing, exception message [Exec exit status not zero. Status [1]]

Скорее всего проблема WildflyЛог jenkins с настройками:

202
Как открыть файл с базой данных , закрытой паролем

Как открыть файл с базой данных , закрытой паролем

есть файл который содержит базу данных- он создаётся кодом с#, но есть загвоздка в том, что он с паролемВот строка подключения от автора проги...

117
Как сделать слияние двух списков с последующей сортировкой?

Как сделать слияние двух списков с последующей сортировкой?

Даны два спискаНеобходимо слить два списка в один, отсортировать по убыванию и вывести

81
После доставания JSONObject из json пропадает поле id. Java. vk api

После доставания JSONObject из json пропадает поле id. Java. vk api

Изначально json приходит в виде (в списке items есть поле id равное 4 у первого элемента !!!):

104