处理元素集合的最佳方法是什么?

时间:2016-03-04 04:36:12

标签: java collections

我有一个文本文件,其中包含一些逐行的字符串(String,String):

  

国家美国
  加利福尼亚州   纽约市   亚特兰大市   县费尔法克斯
  加拿大国家
  纽约市

我的代码应该读取文件一次并跟踪密钥的数量(不同的对),并跟踪每对的第一次出现的顺序。最好的方法是什么? 我的法律钥匙只是“国家”,“州”,“城市”和“县”。 我应该创建一个像

这样的地图
Map<String, Pair<Integer,Integer>>

然后将每个键添加到地图中并更新将跟踪计数和订单的对?还是有更好的方法呢?

2 个答案:

答案 0 :(得分:0)

使用Map<String, Map<Integer,Integer>>

答案 1 :(得分:0)

对我来说,地图或配对不合适,我会有一个内部类:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

import org.apache.commons.lang3.StringUtils;

public class Keys {

    public static void main(String[] args) throws FileNotFoundException {
        Scanner scanner = new Scanner(new File("src/main/resources/META-INF/keys"));
        scanner.useDelimiter("\n");

        Map<String, EntryInfo> stats = new HashMap<>();
        int lineCount = -1;
        while(scanner.hasNext()){
            final String current = scanner.next();
            lineCount++;
            if(StringUtils.isEmpty(current)){
                continue;
            }

            EntryInfo currentEntryInfo = stats.containsKey(current) ? stats.get(current) : new EntryInfo(lineCount);
            currentEntryInfo.incrementCount();
            stats.put(current, currentEntryInfo);
        }
        scanner.close();

        for (String key : stats.keySet()) {
            System.out.println(key + " (" + stats.get(key) + ")");
        }
    }

    public static class EntryInfo{
        private int count = 0;
        private int firstLine = 0;
        public EntryInfo(final int firstLine) {
            this.firstLine = firstLine;
        }
        public void incrementCount() {
            this.count++;
        }
        @Override
        public String toString() {
            return "Count : " + this.count + " First line : " + this.firstLine;
        }
    }
}

打印:

Country USA (Count : 1 First line : 0)
State California (Count : 1 First line : 2)
City Atlanta (Count : 1 First line : 6)
County Fairfax (Count : 1 First line : 8)
Country Canada (Count : 1 First line : 10)
City New York (Count : 2 First line : 4)
相关问题