2016-03-04 89 views
-2

我有一个包含一些对(字符串,字符串)一行行的文本文件:处理元素集合的最佳方法是什么?

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

我的代码应该读取文件并跟踪密钥的计数(不同的对),并跟踪每对的第一次出现的顺序。什么是最好的方式来做到这一点? 我的法定密钥只是“国家”,“州”,“城市”和“县”。 我应该创建一个地图就像

Map<String, Pair<Integer,Integer>> 

然后添加每个键进入地图和更新其要跟踪计数和秩序对???或者有更好的方法来做到这一点?

+0

你的解释是非常困惑。你应该首先思考如何准确地描述问题。它会帮助你理解它。正如你所描述的那样,有“对”的事实根本不影响答案。你只需要一个'LinkedHashSet'。 – Gene

+0

我很困惑。你只需要在那里存储“城市”(并增加柜台)或一对“纽约市”,并增加柜台只为这一对? – MartinS

回答

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) 
0

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

相关问题