Java 如何使用.stream()将存储库中的数据按字母顺序排序

Java 如何使用.stream()将存储库中的数据按字母顺序排序,java,repository,java-stream,Java,Repository,Java Stream,我试图创建一个方法,使用.stream()将存储在存储库中的数据按字母顺序进行排序和输出。目前我有一个方法,可以按CityID按数字顺序对数据进行排序,我将在下面添加这个方法。有没有一种方法可以调整它以按字母顺序按CityName对相同的数据进行排序 城市ID法- private void listCityDataInCityIdOrder() { System.out.format("\033[31m%s\033[0m%n", "City Id Order"); System.

我试图创建一个方法,使用.stream()将存储在存储库中的数据按字母顺序进行排序和输出。目前我有一个方法,可以按CityID按数字顺序对数据进行排序,我将在下面添加这个方法。有没有一种方法可以调整它以按字母顺序按CityName对相同的数据进行排序

城市ID法-

private void listCityDataInCityIdOrder() {
    System.out.format("\033[31m%s\033[0m%n", "City Id Order");
    System.out.format("\033[31m%s\033[0m%n", "=============");
    repository.getItems()
            .stream()
            .sorted()
            .map(c -> c.toString())
            .forEach(str -> System.out.print(str));
}
数据集-

1,"Cartagena","Spain",3
"2015",0.2,33,26,6,"S"
"2016",0.0,33,24,8,"SSW"
"2017",0.0,32,25,6,"E"
2,"Glasgow","Scotland",3
"2015",0.0,19,8,3,"SE"
"2016",0.1,21,11,6,"SE"
"2017",2.1,19,11,9,"SW"
城市模范班-

package model;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;

/**
 *
 * @author mga
 */
public class City implements Comparable<City>{
    private final int id;
    private String cityName;
    private String country;
    private List<YearData> yearDataCollection;

    private static int lastIdAllocated = 0;

    static final char EOLN='\n';
    static final String QUOTE="\"";

    public City() {
        this.id = ++lastIdAllocated;
        this.cityName = "TBC";
        this.country = "TBC";
        this.yearDataCollection = new ArrayList<>();
    }

    public City(String cityName, String country) {
        this.id = ++lastIdAllocated;
        this.cityName = cityName;
        this.country = country;
        this.yearDataCollection = new ArrayList<>();
    }

    public City(String cityName, String country, List<YearData> yearDataCollection) {
        this.id = ++lastIdAllocated;
        this.cityName = cityName;
        this.country = country;
        this.yearDataCollection = yearDataCollection;
    }

    public City(int id, String cityName, String country, List<YearData> yearDataCollection) {
        this.id = id;
        this.cityName = cityName;
        this.country = country;
        this.yearDataCollection = yearDataCollection;
        if (id > City.lastIdAllocated)
            City.lastIdAllocated = id;
    }


    /**
     * @return the id
     */
    public int getId() {
        return id;
    }

    // Methods required:

    public String getCityName() {
        return this.cityName;
    }

    public void setCityName(String cityName) {
        this.cityName = cityName;
    }

    public String getCountry() {
        return this.country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public List<YearData> getYearDataCollection() {
        return this.yearDataCollection;
    }

    public void setYearDataCollection(List<YearData> yearDataCollection) {
        this.yearDataCollection = yearDataCollection;
    }

    public void addYearData(YearData yearData) {
        this.yearDataCollection.add(yearData);
    }


    @Override
    public String toString() {
        return "\nCity Id: " + id + " - City Name: " + cityName +
                " - Country: " + country + "\nData: " + yearDataCollection + "\n";
    }


    public String toString(char delimiter) {
        final char EOLN='\n';
        final String QUOTE="\"";
        String str = Integer.toString(this.id) + delimiter +
                QUOTE + this.cityName + QUOTE + delimiter +
                QUOTE + this.country + QUOTE + delimiter +
                Integer.toString(yearDataCollection.size()) + EOLN;
        for (YearData yearData : yearDataCollection) {
            str += yearData.toString();
        }
        return str;
    }

    public boolean equals(Object object) {
        if (this == object) return true;
        if (!(object instanceof City)) return false;
        if (!super.equals(object)) return false;
        City city = (City) object;
        return getId() == city.getId() &&
                java.util.Objects.equals(getCityName(), city.getCityName()) &&
                java.util.Objects.equals(getCountry(), city.getCountry()) &&
                java.util.Objects.equals(getYearDataCollection(), city.getYearDataCollection());
    }

    public int hashCode() {
        return Objects.hash(super.hashCode(), getId(), getCityName(), getCountry(), getYearDataCollection());
    }

    @Override
    public int compareTo(City compareCity) {

        int cityId =
                ((City) compareCity).getId();

        //ascending order
        return this.id - cityId;

        //descending order
        //return cityId - this.id;
    }


    public static Comparator<City> CityComparator = new Comparator<City>() {
        @Override
        public int compare(City city1, City city2) {

            String cityName1 = city1.getCityName();
            String cityName2 = city2.getCityName();

            //ascending order
            //return cityName1.compareTo(cityName2);

            //descending order
            return cityName2.compareTo(cityName1);
        }
   };

}
包模型;
导入java.util.ArrayList;
导入java.util.Comparator;
导入java.util.List;
导入java.util.Objects;
/**
*
*@作者mga
*/
公共类城市实行可比性{
私有最终int id;
私有字符串cityName;
私人国家;
私人名单数据收集;
私有静态int lastIdAllocated=0;
静态最终字符EOLN='\n';
静态最终字符串引号=“\”;
公共城市(){
this.id=++lastIdAllocated;
this.cityName=“TBC”;
this.country=“TBC”;
this.yearDataCollection=新的ArrayList();
}
公共城市(字符串cityName,字符串country){
this.id=++lastIdAllocated;
this.cityName=cityName;
这个国家=国家;
this.yearDataCollection=新的ArrayList();
}
公共城市(字符串cityName、字符串country、列表年份数据收集){
this.id=++lastIdAllocated;
this.cityName=cityName;
这个国家=国家;
this.yearDataCollection=yearDataCollection;
}
公共城市(int-id、String-cityName、String-country、List-yearDataCollection){
this.id=id;
this.cityName=cityName;
这个国家=国家;
this.yearDataCollection=yearDataCollection;
如果(id>City.LastID已分配)
City.lastIdAllocated=id;
}
/**
*@返回id
*/
公共int getId(){
返回id;
}
//所需方法:
公共字符串getCityName(){
返回this.cityName;
}
公共void setCityName(字符串cityName){
this.cityName=cityName;
}
公共字符串getCountry(){
返回这个国家;
}
公共国家/地区(字符串国家/地区){
这个国家=国家;
}
公共列表getYearDataCollection(){
返回this.yearDataCollection;
}
public void setYearDataCollection(列表yearDataCollection){
this.yearDataCollection=yearDataCollection;
}
public void addYearData(YearData YearData){
this.yearDataCollection.add(yearData);
}
@凌驾
公共字符串toString(){
返回“\nCity Id:“+Id+”-城市名称:“+cityName”+
“-国家:“+Country+”\n数据:“+yearDataCollection+”\n”;
}
公共字符串toString(字符分隔符){
最终字符EOLN='\n';
最后一个字符串引号=“\”;
String str=Integer.toString(this.id)+分隔符+
QUOTE+this.cityName+QUOTE+分隔符+
QUOTE+this.country+QUOTE+分隔符+
Integer.toString(yearDataCollection.size())+EOLN;
对于(YearData YearData:yearDataCollection){
str+=yearData.toString();
}
返回str;
}
公共布尔等于(对象){
如果(this==对象)返回true;
如果(!(城市对象实例))返回false;
如果(!super.equals(object))返回false;
城市=(城市)对象;
return getId()==city.getId()&&
java.util.Objects.equals(getCityName(),city.getCityName())&&
java.util.Objects.equals(getCountry(),city.getCountry())&&
equals(getYearDataCollection(),city.getYearDataCollection());
}
公共int hashCode(){
返回Objects.hash(super.hashCode(),getId(),getCityName(),getCountry(),getYearDataCollection());
}
@凌驾
公共国际比较(城市比较){
国际城市ID=
((城市)比较性);
//升序
返回this.id-cityId;
//降序
//返回cityId-this.id;
}
公共静态比较器CityComparator=新比较器(){
@凌驾
公共整数比较(城市1、城市2){
字符串cityName1=city1.getCityName();
字符串cityName2=city2.getCityName();
//升序
//返回cityName1.compareTo(cityName2);
//降序
返回cityName2.compareTo(cityName1);
}
};
}

当然,将排序的
更改为:

.sorted(Comparator.comparing(City::getCityName))
或使用lambda:

.sorted(Comparator.comparing(c -> c.getCityName()))

您可以简化比较器

public static Comparator<City> CityComparator = new Comparator<City>() {
    @Override
    public int compare(City city1, City city2) {

        String cityName1 = city1.getCityName();
        String cityName2 = city2.getCityName();

        //ascending order
        //return cityName1.compareTo(cityName2);

        //descending order
        return cityName2.compareTo(cityName1);
    }
};

.sorted(…)
方法有一个重载,根据。在询问API可以提供有用信息的问题时,请首先检查API。您不需要调用
toString()
来打印。您的
等于
hashCode
实现没有意义。当您在直接扩展
java.lang.Object
的类中调用它们的
super
实现时,对象将只与自身相等。这与没有自己的
equals
hashCode
的实现没有什么不同。
T
应该被任何类型的
存储库所取代。getItems()
返回,例如,如果它返回
,那么你就需要排序
(Comparator.comparating(City::cityName))
其中,
cityName
是模型中存储城市名称的任何属性的占位符,如果您不明白我说的话,请发布模型类及其属性。我已按上述方式实现,现在天气数据输出正确,我唯一的问题是,它为每一组数据显示了错误的城市,即显示的不是“卡塔赫纳”,而是“格拉斯哥”。“你知道怎么解决这个问题吗?”约瑟夫伯克我相信,因为比较器h
Comparator<City> cityComparatorSimplified = Comparator
        .comparing(City::getCityName).reversed(); // reverse for descending order
repository.getItems().stream()
            .sorted(cityComparatorSimplified)
            .map(Object::toString)
            .forEach(System.out::print);