简体   繁体   English

用Java中的文本文件中的字符串排序数字

[英]Sorting Numbers with Strings in text file in Java

The goal is to have a sorted input.txt such as: 目标是有一个已排序的input.txt,例如:

1 one
2 two
4 four
10 ten

From an input.txt of: 来自input.txt:

2 two
4 four
1 one
10 ten

So far in my code I have sorted the number array and now I have to change the String array since it's paired with the num array. 到目前为止,在我的代码中,我已经对数字数组进行了排序,现在我必须更改String数组,因为它与num数组配对。 How do I do that? 我怎么做?

import java.util.*;
import java.io.*;
//Noah Cavazos

public class SortingNumbers{
   public static void main(String[] args) throws FileNotFoundException {
      Scanner fin = new Scanner(new File("input.txt"));
      int[] nums = new int[100];
      String[] texts = new String[100];
      int cnt = 0;
      while(fin.hasNextInt()){
         nums[cnt] = fin.nextInt();
         texts[cnt] = fin.nextLine();
         cnt++;
      }
      int[] Numbers = new int[cnt];
      String[] Words = new String[cnt];
      for(int i = 0; i < Numbers.length; i++){
         Numbers[i] = nums[i];
         Words[i] = texts[i];
         //System.out.println(Numbers[i] + Words[i]);
      }
      Arrays.sort(Numbers);
      //Arrays.sort(Words); < Alphabetically

   }

}

Because you are keeping the strings and the numbers in separate arrays, once you sort one of the arrays you lose the relationships between the string-number pairs. 因为您将字符串和数字保存在单独的数组中,所以一旦对其中一个数组进行排序,就会丢失字符串数字对之间的关​​系。

As mentioned by @Andrew S, the way to do this is to create a new class ( Pair ) in which you hold both the number and the string. 正如@Andrew S所提到的,这样做的方法是创建一个新类( Pair ),其中包含数字和字符串。 You will read from the file into an array of objects of type Pair , instead of reading the numbers and strings separately. 您将从文件读取到Pair类型的对象数组,而不是分别读取数字和字符串。 When the array is sorted, the numbers and their corresponding texts will be sorted together. 对数组进行排序后,数字及其对应的文本将一起排序。

To be able to sort an array containing elements of type Pair , we need to specify how exactly to compare two pairs. 为了能够对包含Pair类型元素的数组进行排序,我们需要指定如何比较两对。 This is where the Comparator comes in. It will tell the sorting function the criteria by which the objects in the array will be compared. 这就是Comparator用武之地。它将告诉排序函数比较数组中对象的标准。 In this case, two Pair objects are compared by their number fields. 在这种情况下,两个Pair对象按其number字段进行比较。

public class Pair {

  private int number;
  private String text;
  // getters and setters, constructor, toString() etc.
}


public static void main(String[] args) throws FileNotFoundException{
    Scanner fin = new Scanner(new File("input.txt"));
    int[] nums = new int[100];
    String[] texts = new String[100];
    int cnt = 0;
    while(fin.hasNextInt()){
        nums[cnt] = fin.nextInt();
        texts[cnt] = fin.nextLine();
        cnt++;
    }
    Pair[] pairs = new Pair[cnt];
    for(int i = 0; i < cnt; i++){
        pairs[i] = new Pair(nums[i], texts[i]);
    }
    Arrays.sort(pairs, new Comparator<Pair>() {
        @Override
        public int compare(Pair o1, Pair o2) {
            return Integer.compare(o1.getNumber(), o2.getNumber());
        }
    });
    for (Pair p: pairs) {
        System.out.println(p);
    }

}

I'd like to recommend an easier approach to read your text file and sorting the items. 我想建议一种更简单的方法来读取您的文本文件并对项目进行排序。

List<SimpleEntry<Integer, String>> result;
try (Stream<String> stream = Files.lines(Paths.get("input.txt"))) {
   result = stream.map(s -> s.split("\\s"))
                  .map(a -> new SimpleEntry<>(Integer.parseInt(a[0]), a[1]))
                  .sorted(Comparator.comparingInt(SimpleEntry::getKey))
                  .collect(Collectors.toCollection(ArrayList::new));
} catch (IOException e) { e.printStackTrace(); }

This solution uses SimpleEntry to contain both the integer value and the String value so that after sorting we can maintain related data. 此解决方案使用SimpleEntry包含整数值和String值,以便在排序后我们可以维护相关数据。

On another note, you may want to create your own custom class with these two fields as mentioned by @Andrew S instead of SimpleEntry . 另外,您可能希望使用@Andrew S而不是SimpleEntry提到的这两个字段创建自己的自定义类。

You cannot sort one arrays without another, because you lost relations (which row in unsoted arrays belongs to one in sorted). 您不能在没有另一个数组的情况下对一个数组进行排序,因为您丢失了关系(未通知数组中的哪一行属于已排序的数组)。

To fix this, you could maintain the relation in a map, but smarter is to create class and sort instances of such class (Comparable/Comparator). 要解决这个问题,您可以在地图中维护关系,但更聪明的是创建此类(Comparable / Comparator)的类和排序实例。

To do this you have to link the integers to the strings, you can do this with a HashMap were save while you are reading the file in the integers as key a the word as value. 要做到这一点,你必须将整数链接到字符串,你可以用HashMap进行保存,同时你在整数中读取文件作为关键字作为值。 After sorting your numbers array you can simply cycle through the array of numbers and make a new array of strings where you put the value to the integer in it which you saved before in the HashMap. 在对数字数组进行排序之后,您可以简单地循环遍历数字数组并创建一个新的字符串数组,您可以将值放入之前在HashMap中保存的整数。

Another method would be to write your own sorting algorithm and change the string array as you change the integer array in the same way. 另一种方法是编写自己的排序算法,并在以相同方式更改整数数组时更改字符串数组。

When you track a pair of values, one value leading to the other value, that is commonly known as a key-value or attribute-value pair . 跟踪一对值时,一个值导向另一个值,通常称为键值或属性值对

Map

In Java, we track one value by another using the Map interface. 在Java中,我们使用Map接口跟踪另一个值。 When you put in a key-value pair, you can later retrieve the value by specifying the key. 放入键值对时,可以稍后通过指定键来检索值。 Like a dictionary, where a word leads to a definition. 像字典一样,单词导致定义。

SortedMap

If you want the keys kept in sorted order, use the SortedMap sub-interface. 如果希望按键按顺序保存,请使用SortedMap子接口。

TreeMap

One implementation of a SortedMap that comes bundled with Java is the TreeMap class. 与Java捆绑在一起的SortedMap一个实现是TreeMap类。

Using Java Generics , you specify the data type to used as keys and the data type to be used as values. 使用Java Generics ,指定要用作键的数据类型和要用作值的数据类型。 In our case here, that would be Integer and String . 在我们的例子中,那将是IntegerString

SortedMap< Integer , String > map = new TreeMap<>() ;

As you gather your inputs, parse the input meant to be a number as a Integer . 在收集输入时,将输入解析为数字作为Integer Then store with its partnering String object into the TreeMap . 然后将其合作的String对象存储到TreeMap

Integer integer = Integer.getInteger( "1" ) ;
String string = "one" ;

map.put( integer , string ) ;

When you loop these entries, they will be presented to you in the sorted order of the keys, sorted numerically because they are of type Integer . 当您循环这些条目时,它们将按键的排序顺序呈现给您,以数字方式排序,因为它们是Integer类型。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM