阅读唯一价值观

时间:2015-02-19 11:57:16

标签: java

我编写了一段代码,用于从文本文件中的列读取值。为了输出值的数量,我使用了' length'哪个工作正常..但我只需要计算唯一值的数量。

public class REading_Two_Files {

public static void main(String[] args) {

    try {
        readFile(new File("C:\\Users\\teiteie\\Desktop\\RECSYS\\yoochoose-test.csv"), 0,( "C:\\Users\\teiteie\\Desktop\\RECSYS\\yoochoose-buys.csv"), 3);
     //readFile(new File(File1,0, File2,3);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

//// 0 - 将从file1打印列     // 3 - 将从文件2打印列

private static void readFile(File fin1,int whichcolumnFirstFile,String string,int whichcolumnSecondFile) throws IOException {
    //private static void readFile(File fin1,int whichcolumnFirstFile,String string,int whichcolumnSecondFile) throws IOException
    // code for this method.
    //open the two files.

    int noSessions = 0;
    int noItems = 0;
//  HashSet<String> uniqueLength = new HashSet<String>();


    FileInputStream fis = new FileInputStream(fin1); //first file
    FileInputStream sec = new FileInputStream(string); // second file

//Construct BufferedReader from InputStreamReader
    BufferedReader br1= new BufferedReader(new InputStreamReader(fis));
    BufferedReader br2= new BufferedReader(new InputStreamReader(sec));

    String lineFirst = null, first_file[];
    String lineSec = null, second_file [];

    while ((lineFirst = br1.readLine()) != null && (lineSec = br2.readLine()) != null) {
        first_file= lineFirst.split(",");
        second_file = lineSec.split(",");

        //int size = data[].size();

    System.out.println(first_file[0]+" , "+second_file[0]);



    if(first_file.length != 0){
        noSessions++;
        }

        if(second_file.length != 0)  {
        noItems ++;
        }



        }

        br1.close();
        br2.close();
        System.out.println("no of sessions "+noSessions+"\nno of items "+noItems );


    }


}

2 个答案:

答案 0 :(得分:1)

要仅计算唯一值,我们通常使用Set,因为它们被指定为仅包含唯一值。

  

不包含重复元素的集合。更正式地说,集合不包含元素对e1和e2,使得e1.equals(e2)和至多一个null元素。正如其名称所暗示的,该界面模拟数学集抽象。

基本上 - 将所有值放在Set中(通常是HashSet是最有效的,但如果你想要并发有更好的选择)然后将Set.size()作为您输入的唯一值的数量。

答案 1 :(得分:0)

只是为了给你一些灵感:

Map<String,Integer> lAllWordsWithCount = new HashMap<String, Integer>();
    String[] lAllMyStringToCount = {"Hello", "I", "am", "what", "I", "am"};
    for (String lMyString : lAllMyStringToCount) {
      int lCount = 1;
      if (lAllWordsWithCount.containsKey(lMyString)){
        lCount = lAllWordsWithCount.get(lMyString) +1;
      }
      lAllWordsWithCount.put(lMyString, lCount);
    }
    for(String lStringKey : lAllWordsWithCount.keySet()){
      System.out.println(lStringKey+" count="+lAllWordsWithCount.get(lStringKey));
    }

将导致:

what count=1
am count=2
I count=2
Hello count=1