—Đây là phương thức add vị trí vào từng phần tử
public void add(String word, int position) throws FileNotFoundException {
if (map.containsKey(word)) {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(position);
map.put(word, list);
} else {
ArrayList<Integer> pos = new ArrayList<Integer>();
pos.add(position);
map.put(word, pos);
}
}
—Đây là phương thức sắp xếp và in ra sô thư tự của từng phần tử trong file
public void displayText(String file) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(file));
int position = 1;
String line = null;
while (true) {
line = reader.readLine();
if (line == null)
break;
StringTokenizer token = new StringTokenizer(line, ", ");
int count = token.countTokens();
while (token.hasMoreTokens()) {
String word = token.nextToken();
int n = 1;
if (n == count) {
this.add(word, -position);
} else {
this.add(word, position);
}
position++;
n++;
}
}
reader.close();
ArrayList<Map.Entry<String, ArrayList<Integer>>> list = new ArrayList<Map.Entry<String, ArrayList<Integer>>>();
list.addAll(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<String, ArrayList<Integer>>>() {
@Override
public int compare(Map.Entry<String, ArrayList<Integer>> o1, Map.Entry<String, ArrayList<Integer>> o2) {
int n = o1.getKey().compareTo(o2.getKey());
return n;
}
});
System.out.println(list);
}
—Nhưng khi em run thì tự nhiên nó chia list làm 2 phần rồi mới sắp xếp từng phần em không hiểu <em thấy code của em đúng> mong anh chị giải đáp giúp em vơi
Em cảm ơn ak.