使用java集合框架在文本文件中对两列进行排序

时间:2014-08-23 12:11:21

标签: java collections arraylist

我有一个包含

等行的输入文件
21,mahesh
12,suresh
23,rajesh
25,lokesh

通过使用ArrayList,我编写了下面的代码来处理升序和降序

import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

public class FileRead {
    public static void main(String[] args)throws IOException {
        Scanner s = new Scanner(new FileReader("D:\\Numbers.txt"));
        ArrayList<String> al = new ArrayList<String>();

        while (s.hasNextLine()) {
            String line = s.nextLine(); 
            al.add(line);
        }
        Collections.sort(al,Collections.reverseOrder());

        for (String i: al)
        System.out.println(i);
    }
}

这产生了以下输出

 - 25,lokesh
 - 23,rajesh
 - 21,mahesh
 - 12,suresh 

$在上面的代码中,当我使用Collections.sort()操作将整行作为一行时,它可以工作。

$如果我接受输入如下面的字符串列第一个和整数列接下来上面的代码不能正常工作它将使用字符串值分配字母顺序,我想通过仅使用整数而不是字符串值来排序数据请帮帮我的朋友

 - mahesh,21
 - suresh,12
 - rajesh,23
 - lokesh,25

3 个答案:

答案 0 :(得分:2)

首先读取文件将其存储在Map

Map map = new TreeMap();
while(true)
{
 String line = bufferedReader.readLine();
 if(line == null)
 break;
 else {
   String arr[] = line.split(",");
   for(int i=0;i<arr.length-1;i++)
   {
       map.put(arr[i],arr[i+1]);
   }}
}

使用Comparator

对其进行排序
List list = new LinkedList(map.entrySet());
Collections.sort(list, new Comparator() {
public int compare(Object o1, Object o2) {
  return ((Comparable) ((Map.Entry) (o2)).getValue())
                        .compareTo(((Map.Entry) (o1)).getValue());
   }
});

最后取消结果

Map result = new LinkedHashMap();
for (Iterator it = list.iterator(); it.hasNext();) {
    Map.Entry entry = (Map.Entry)it.next();
    result.put(entry.getKey(), entry.getValue());
}
System.out.println(result.toString());

从比较器返回时,用于关闭开关o1和o2。

对于第二种输入

    List list = new LinkedList(map.keySet());
    Collections.sort(list);
    Set set = map.entrySet();
    Map result = new LinkedHashMap();
    for (Iterator it = set.iterator(); it.hasNext();) {
        Map.Entry entry = (Map.Entry)it.next();
        result.put(entry.getKey(), entry.getValue());
    }
    System.out.println(result.toString());

答案 1 :(得分:1)

以下内容允许您使用LineEntry类将信息解析为适当的类型以包装数据。它将提供对Integer值的正确排序,而不是将它们视为字符串并应用字母顺序。

import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

public class FileRead {

    public static void main(String[] args) throws Exception {
        Scanner s = new Scanner(new InputStreamReader(FileRead.class.getResourceAsStream("/numbers.txt")));
        s.useDelimiter("[,\\s]");

        ArrayList<LineEntry> lineEntryList = new ArrayList<LineEntry>();
        while (s.hasNextLine()) {
            int amount = s.nextInt();
            String value = s.next();
            LineEntry lineEntry = new LineEntry(value, amount);
            lineEntryList.add(lineEntry);
        }
        Collections.sort(lineEntryList, Collections.reverseOrder());

        for (LineEntry i : lineEntryList) {
            System.out.println(i);
        }

    }

    public static class LineEntry implements Comparable<LineEntry>{

        private String value;
        private Integer amount;

        public LineEntry(String value, Integer amount) {
            this.value = value;
            this.amount = amount;
        }

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }

        public Integer getAmount() {
            return amount;
        }

        public void setAmount(Integer amount) {
            this.amount = amount;
        }

        @Override
        public String toString() {
            return "LineEntry{" + "value=" + value + ", amount=" + amount + '}';
        }

        @Override
        public int compareTo(LineEntry o) {
            int compareTo = o.getAmount().compareTo(amount);
            if (compareTo == 0) {
                compareTo = o.getValue().compareTo(value);
            }
            return compareTo;
        }

}

答案 2 :(得分:0)

最好创建一个不同的类,其中包含以逗号分隔的每一行中的数据作为该类的变量,以便将来如果您在同一行中有多列数据,那么代码可以是可伸缩的,您还可以创建自定义比较器根据您的排序条件: -

public class FileRead {

    public static void main(String[] args) throws Exception {
        Scanner s = new Scanner(new FileReader("E:\\Numbers.txt"));        
        List<FileObject> al = new ArrayList<FileObject>();
        while (s.hasNextLine()) {
            String line = s.nextLine();            
            al.add(new FileObject().createFileObject(line));
        }
        Collections.sort(al,new FileObjectComparator());

        for (FileObject i: al)
            System.out.println(i);

    }

}

class FileObject {

    private int id;
    private String name;

    public FileObject createFileObject(String line) {
        if(line != null && !line.isEmpty()) {
            for(String str : line.split(",")) {
                str = str.trim();
                if(str.matches("([\\d]*)")) {
                    id = Integer.valueOf(str);
                } else {
                    name = str;
                }
            }
        }
        return this;
    }

    ... // getters and setters
    @Override
    public String toString() {      
        return "[ID] "+id+ " [Name] "+name ;
    }
}

class FileObjectComparator implements Comparator<FileObject> {

    @Override
    public int compare(FileObject o1, FileObject o2) {      
        return o2.getId() - o1.getId();
    }

}