简体   繁体   English

如何像其他排序列表一样对 ArrayList 进行排序?

[英]How to sort ArrayList like other sorted list?

I have two ArrayList s.我有两个ArrayList One is of the Double type and contains distances.一个是Double类型,包含距离。 The other one is of the String type and contains city types.另一种是String类型,包含城市类型。

These are the lists:这些是列表:

private ArrayList<Double> distance_list = new ArrayList<Double>();
distance.add(123.43);
distance.add(450.43);
distance.add(230.65);

private ArrayList<String> city_list = new ArrayList<String>();
city_list.add("Munich");
city_list.add("Berlin");
city_list.add("Frankfurt");

Collections.sort(distance_list); //to get the closest distance first

How can I sort the city_list in the same order to the matching distances?如何以与匹配距离相同的顺序对city_list进行排序?

NavigableMap / SortedMap NavigableMap / SortedMap

Use a Map instead.请改用Map A map pairs two items together, in a key-value relationship. map 以键值关系将两个项目配对在一起。 Ask for the key to access its value partner.索要访问其价值合作伙伴的密钥。

Using a NavigableMap or SortedMap keeps, the keys in order.使用NavigableMapSortedMap可以保持键的顺序。

NavigableMap< Double , String > map = new TreeMap<>() ;
map.add( 123.43d , "Munich" ) ;
…

You can then loop that map.然后,您可以循环该 map。 See: How to Loop in NavigableMap in Java ;请参阅:如何在 Java 中的 NavigableMap 中循环

for( Double key : map.keySet() )
{
    String city = map.get( key ) ;
    System.out.println( city + " = " + key ) ;
}

Here is a diagram graphic I made as an overview of the Map implementations bundled with Java 11. You can see SortedMap interface was added first, then later extended by NavigableMap interface.这是我制作的图表图形,作为与 Java 11 捆绑的Map实现的概述。您可以看到首先添加了SortedMap接口,然后通过NavigableMap接口进行了扩展。

在此处输入图像描述

You'll want to create a class that pairs both values and implements the Comparable interface, such as:您需要创建一个 class 将两个值配对并实现 Comparable 接口,例如:

public class City implements Comparable<City> {

    private Double distance;
    private String name;

    // constructor, getters, setters

    @Override
    public int compareTo(City city) {
        return (double)(this.distance - city.getDistance());
    }
}

Then build a Treemap or some other Map type that keeps things sorted.然后构建一个 Treemap 或其他一些 Map 类型,以保持事物的排序。 I assume you wish to sort by distance.我假设您希望按距离排序。

//Create TreeMap
TreeMap<Double, String> cities = new TreeMap();

//Add cities
cities.put(123.43, "Munich");

The items will be sorted by the distances values!这些项目将按距离值排序!

Try it out and post your code if you need more help.如果您需要更多帮助,请尝试并发布您的代码。

You can do it in 2 steps您可以分两步完成

  • You create an englobing class您创建一个 englobing class
    • The class must implements Comparable (it is used in Collections.sort()) class 必须实现 Comparable(在 Collections.sort() 中使用)
  • Then you sort with Collections.sort()然后你用 Collections.sort() 排序
class DistanceCity implements Comparable<DistanceCity>  {
    private Double distance;
    private String city;

    public DistanceCity(Double distance, String city) {
        this.distance = distance;
        this.city = city;
    }

    @Override
    public int compareTo(DistanceCity o) {
        return distance.compareTo(o.distance);
    }

    @Override
    public String toString() {
        return "DistanceCity{" + "distance=" + distance + ", city='" + city + "'}";
    }
}
private ArrayList<DistanceCity> liste;
liste = new ArrayList<>();
liste.add(new DistanceCity(123.43,"Munich"));
liste.add(new DistanceCity(450.43,"Berlin"));
liste.add(new DistanceCity(230.65,"Frankfurt"));

System.out.println(liste); // unordered
//[DistanceCity{distance=123.43, city='Munich'}, DistanceCity{distance=450.43, city='Berlin'}, DistanceCity{distance=230.65, city='Frankfurt'}]

Collections.sort(liste);

System.out.println(liste); // ordered
// [DistanceCity{distance=123.43, city='Munich'}, DistanceCity{distance=230.65, city='Frankfurt'}, DistanceCity{distance=450.43, city='Berlin'}]

A full implementation with Comparable and example带有 Comparable 和示例的完整实现

class City implements Comparable<City>{
  public String name = null;
  public Double distance = 0.0;

  public City(String name, Double distance){
    this.name = name;
    this.distance = distance;
  }

  @Override
  public int compareTo(City o){
    return this.distance.compareTo( o.distance );
  }

  @Override
  public String toString(){
    return this.name;
  }

}


public class CitiesDemo{
  public static void main (String[] args ){
  City munich = new City("Munich", 123.43);
  City berlin = new City("Berlin", 450.43);
  City frankfurt = new City("Frankfurt", 230.65);

  java.util.List<City> cities = new java.util.ArrayList<City>();
  cities.add( munich );
  cities.add( berlin );
  cities.add( frankfurt );
  java.util.Collections.sort( cities );
  System.out.println( cities );
  }

}

Will return:将返回:

~/ (main)$ javac CitiesDemo.java 

~/ (main)$ java CitiesDemo

[Munich, Frankfurt, Berlin]

~/ (main)$ 

Or, you can test it here: https://ideone.com/fbbLv6或者,您可以在这里进行测试: https://ideone.com/fbbLv6

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 stream().sorted() 对带有对象的 ArrayList 进行排序 - How to sort an ArrayList with object using stream().sorted() 如何对 Arraylist 进行排序,使其集合按值列表排序 - How do I sort an Arraylist so its collection is sorted by a list of values 如何在其他列表中对ArrayList进行排序 - How To Sort ArrayList in Different List Java:如何在不使用 Sort() 的情况下基于自定义对象 ArrayList 创建排序字符串 ArrayList - Java: How to create a sorted string ArrayList based on Custom object ArrayList without using Sort() 如何对ArrayList进行排序 <String> 包含ArrayList的元素 <HashMap<String, String> &gt;已由比较器排序? - How to sort ArrayList<String> containing elements of ArrayList<HashMap<String, String>> that has been sorted by a comparator? 与其他int-arraylist一样对int-arraylist进行排序(不相同的indexOf值) - Sort int-arraylist like other int-arraylist (not same indexOf values) 如何对两个 arrays 进行排序,其中一个是基于另一个排序的? - How to sort two arrays with one being sorted based on the sorting of the other? 如何从2个不同的arraylist中排序arraylist? 像两个arraylist,性别和学生。 如何按性别查看学生详细信息 - How can i sorted arraylist from 2 different arraylist? like two arraylist, gender and student. How to view the student details in genderwise 根据已排序的 ArrayList 对 ArrayList 进行排序的最佳方法是什么? - What is the best way to sort an ArrayList based on a already sorted ArrayList? ArrayList一个循环排序,另一个未排序 - ArrayList One loop sorted, the other unsorted
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM