【问题标题】:link or merge 2 arrays into 1 and sort them in java将 2 个数组链接或合并为 1 个并在 java 中对它们进行排序
【发布时间】:2013-11-05 07:32:55
【问题描述】:

是否可以合并两个数组(一维),即 string 和 int 并对它们进行排序?例如:

String name[] = {"Percy", "Daniel, "Layla"};
int marks[] = {90, 87, 91};

Arrays.sort (name);
for(int i = 0; i < name.length; i++)
    System.out.println( (i+1) + ". "+ name[i] + "\t\t" + marks[i]);

如果我想对它们进行排序,我希望输出是这样的:

// before sorting
1. Percy       90
2. Daniel      87
3. Layla       91

// after sorting
1. Daniel      90
2. Layla       87
3. Percy       91

// the actual output that i wanted
1. Daniel      87
2. Layla       91
3. Percy       90

你会建议我做什么?如何链接这两个数组并根据它们的名称对它们进行排序?或者我如何合并它们?有没有我能理解的简单方法?当我在网上到处阅读有关使用比较器、合并和所有内容时,我还不是很清楚。

我是 Java 新手。那么有什么适合初学者的方法吗?

【问题讨论】:

    标签: java arrays sorting merge


    【解决方案1】:

    这是我新手时通常做的:

            String name[] = {"Percy","Daniel","Layla"};
            int marks[] = {90, 87, 91};
            String merged[] = new String[name.length];
            for (int i=0; i< name.length; i++) {
                merged[i] = name[i]+"=="+marks[i];
            }
            Arrays.sort(merged);
            for(int i = 0; i < merged.length; i++) {
                System.out.println( (i+1) + ". "+ merged[i].split("==")[0] + "\t\t" + merged[i].split("==")[1]);
            }
    

    【讨论】:

      【解决方案2】:

      使用Map 可以轻松解决您的问题。 Map 是一个类,可用于存储链接的数据对,其中每对数据都有一个“键”和一个“值”。一旦存储在地图中,如果您有相应的键,您可以快速查找任何值。还有一种方法可以遍历或列出地图中的所有键。

      这是一个简单的程序,展示了如何使用Map 来解决问题:

      import java.util.*;
      
      public class Example
      {
          public static void main(String[] args)
          {
              String[] name = new String[] {"Percy", "Daniel", "Layla"};
              int[] marks = new int[] {90, 87, 91};
      
              // First create a TreeMap to hold the data.  A TreeMap is a special
              // kind of Map which keeps the keys in sorted order for you.
              // In this TreeMap, the keys will be Strings and the values
              // will be Integers.
              TreeMap<String, Integer> map = new TreeMap<String, Integer>();
      
              // Next, link each name in the names array to the corresponding mark
              // by putting them in the TreeMap.  Each name becomes a key
              // in the map, and each mark is a value.
              for (int i = 0; i < name.length; i++)
              {
                  map.put(name[i], marks[i]);
              }
      
              // Now we can iterate over the keys in the map, and for each key
              // retrieve the corresponding value.  The TreeMap guarantees
              // the keys will be in sorted order.
              for (String key : map.keySet())
              {
                  System.out.println(key + "\t" + map.get(key));
              }
          }
      }
      

      这是输出:

      Daniel  87
      Layla   91
      Percy   90
      

      【讨论】:

        【解决方案3】:

        假设您有唯一的名称,您可以使用 HashMap 来获得名称标记对。 Map 返回其键集(在本例中为名称)排序。

        String name[] = {"Percy", "Daniel", "Layla"};
        int marks[] = {90, 87, 91};
        
        if (name.length!=marks.length){
            System.exit(0);
        }
        HashMap<String, Integer> hm = new HashMap<String, Integer>();
        for(int i=0;i<name.length;i++){
            hm.put(name[i], marks[i]);
        }
        
        ArrayList<String> keys = new ArrayList<String>(hm.keySet()); //for descending order
        for(int i=keys.size()-1, j=0; i>=0;j++,i--){
            System.out.println((j+1)+". "+keys.get(i)+"\t\t"+hm.get(keys.get(i)));
        }
        

        【讨论】:

        • 老兄,问题中有错字,我已修正。安息吧!如果您对我的回答有任何意见,我很乐意讨论它们:)
        • 在您的链接上,这家伙正在谈论代码,因为这是一些“查找我的错误”问题。这里提出的问题不是关于“我的代码有什么问题?”,而是关于“最好的方法是什么?”。我同意您的关注,但在此问题的上下文中无效。
        • read the second paragraph :) "这不是导致代码无法工作的原因"。对于这个问题,它是一个错字。小报价是没有问题的。再一次,这里提出的问题不是关于“我的代码有什么问题?”,而是关于“最好的方法是什么?”。
        【解决方案4】:

        没有标准解决方案。试试这个

        static void sort(String[] name, int[] marks) {
            for (int i = 0; i < name.length; i++) {
                for (int j = i; j > 0 && (name[j - 1]).compareTo(name[j]) > 0; j--) {
                    swap(name, j, j - 1);
                    swap(marks, j, j - 1);
                }
            }
        }
        
        private static void swap(String[] x, int a, int b) {
            String t = x[a];
            x[a] = x[b];
            x[b] = t;
        }
        
        private static void swap(int[] x, int a, int b) {
            int t = x[a];
            x[a] = x[b];
            x[b] = t;
        }
        

        这是来自 Arrays.sort 的插入排序算法的修改版本

        【讨论】:

          【解决方案5】:

          试试这样的:

                  String name[] = {"Percy", "Daniel", "Layla"};
                  int marks[] = {90, 87, 91};
                  ArrayList<String> arrayList = new ArrayList<String>();
                  System.out.println("Before Sorting..");
                  for (int i = 0; i < name.length; i++) {
                      arrayList.add(name[i] + " " + marks[i]);
                      //Before Sorting
                      System.out.println(i + 1 + " " + name[i] + " " + marks[i]);
                  }
          
                  Collections.sort(arrayList);
                  //After Sorting
                  System.out.println("After Sorting..");
                  for (int i = 0; i < arrayList.size(); i++) {
                      System.out.println(i + 1 + " " + arrayList.get(i));
                  }
          

          【讨论】:

            【解决方案6】:

            您要求为初学者提供 Java 课程。网上有很多关于比较器、树集和 Java 中所有其他内容的示例。您肯定需要花时间阅读您看到的所有内容,但其中许多示例非常清晰。如果您正在尝试学习某些东西,但它对您不起作用,请不要花更多时间在上面。再次谷歌,即使它是第 15 或第 20 解释最终对你有用。这是很常见的。在你理解之前不要阅读过去的任何东西。

            当然有一个类来存储实现 Comparable 的字符串,正如@regulus 建议的那样,除了使用名称而不是标记 :) 将标记也存储在类中,以供将来参考,或者如果您希望将其用于二次比较(在比较名称之后)。这会给你的元素一个自然的顺序。在创建每个对象实例时,...

            将它们插入到 Java 的 TreeSet 实例中。以下是它的用法示例:

            import java.util.TreeSet;
            import java.util.Iterator;
            
            public class IterateThroughElementsOfTreeSetExample {
            
              public static void main(String[] args) {
            
                //create object of TreeSet
                TreeSet tSet = new TreeSet();
            
                //add elements to TreeSet object
                tSet.add(new Integer("1"));
                tSet.add(new Integer("2"));
                tSet.add(new Integer("3"));
            
                //get the Iterator
                Iterator itr = tSet.iterator();
            
                System.out.println("TreeSet contains : ");
                while(itr.hasNext())
                  System.out.println(itr.next());
              }
            }
            

            它会非常快,因为它会在您插入键时进行排序。

            【讨论】:

              【解决方案7】:

              将字符串数组和整数数组合并是没有意义的。除非性能是您优先考虑的问题,否则以面向对象的方式实现解决方案要好得多。 我会创建一个包含名称和标记的类。因此,每个名称和标记对都会有一个此类的实例。然后我将实现 Comparable 接口,使此类可排序。

              class Grade implements Comparable<Grade>{
                  String name;
                  int mark;
              
                  public int compareTo(Grade o) {
                      return name.compareTo(o.name);
                  }
              }
              

              【讨论】:

              • 这很好,但我认为 OP 想按名称排序,而不是按标记。
              【解决方案8】:

              创建一个新的 Comparable 类NameScore

              public class NameScore implements Comparable<NameScore> {
              
              private final String name;
              private final int marks;
              
              public NameScore(String name, int marks) {
                  this.name = name;
                  this.marks = marks;
              }
              
              @Override
              public int compareTo(NameScore other) {
                  // compare by name
                  return this.name.compareTo(other.name);
              
                  // compare by (ascending) marks 
                  //return this.marks - other.marks;
              }
              
              @Override
              public String toString() {
                  return "" + name + " (" + marks + ")";
              }
              }
              

              以下是如何使用 NameScore 来解决您的问题:

              public static void main(String[] args) {
                  String name[] = {"Percy", "Daniel", "Layla"};
                  int marks[] = {90, 87, 91};
              
                  List<NameScore> list = new LinkedList<NameScore>();
                  for (int i = 0; i < marks.length; i++) {
                      NameScore element = new NameScore(name[i], marks[i]);
                      list.add(element);
                  }
              
                  System.out.println("BEFORE : "+list);
              
                  Collections.sort(list);
              
                  System.out.println(" AFTER : "+list);
              }
              

              【讨论】:

                【解决方案9】:

                可以通过两种方式完成

                1. 如果仅按名称排序,则将名称和标记添加到 TreeMap 作为键和值,自动排序。
                2. 如果需要按两者排序,请使用这些变量创建类并实现可比较的接口。

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 2023-03-18
                  • 2020-08-09
                  • 2022-10-04
                  • 2016-09-23
                  • 1970-01-01
                  • 2013-12-03
                  • 1970-01-01
                  • 1970-01-01
                  相关资源
                  最近更新 更多