根据长度将单词从文本文件分组到Arraylist [英] Grouping of words from a text file to Arraylist on the basis of length

查看:134
本文介绍了根据长度将单词从文本文件分组到Arraylist的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class JavaApplication13 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
         BufferedReader br;
        String strLine;
        ArrayList<String> arr =new ArrayList<>();
        HashMap<Integer,ArrayList<String>> hm = new HashMap<>();
        try {
            br = new BufferedReader( new FileReader("words.txt"));
            while( (strLine = br.readLine()) != null){
                arr.add(strLine);
            }
        } catch (FileNotFoundException e) {
            System.err.println("Unable to find the file: fileName");
        } catch (IOException e) {
            System.err.println("Unable to read the file: fileName");
        }


        ArrayList<Integer> lengths = new ArrayList<>(); //List to keep lengths information 


        System.out.println("Total Words: "+arr.size()); //Total waords read from file

        int i=0;
        while(i<arr.size()) //this loop will itrate our all the words of text file that are now stored in words.txt
        {
            boolean already=false;
            String s = arr.get(i);
            //following for loop will check if that length is already in lengths list.
            for(int x=0;x<lengths.size();x++)
            {
                if(s.length()==lengths.get(x))
                    already=true;
            }
           //already = true means file is that we have an arrayist of the current string length in our map
            if(already==true)
            {

                hm.get(s.length()).add(s); //adding that string according to its length in hm(hashmap)
            }
            else
            {
                    hm.put(s.length(),new ArrayList<>()); //create a new element in hm and the adding the new length string
                    hm.get(s.length()).add(s);
                    lengths.add(s.length());

            }

            i++;
        }
        //Now Print the whole map
        for(int q=0;q<hm.size();q++)
        {
            System.out.println(hm.get(q));
        }
    }

}

这种方法正确吗?

说明:

  1. 将所有单词加载到ArrayList中.
  2. 然后遍历每个索引并检查单词的长度,将其添加到包含该长度的字符串的ArrayList中,其中这些ArrayList映射到包含其单词长度的哈希图中.

推荐答案

首先,您的代码仅适用于逐行包含一个单词的文件,因为您正在将整行作为单词处理.为了使代码更具通用性,您必须通过将每一行拆分为多个单词来对其进行处理:

Firstly, your code is working only for the files which contain one word by line as you're processing whole lines as words. To make your code more universal you have to process each line by splitting it to words:

String[] words = strLine.split("\\s+")

第二,您不需要任何临时数据结构.从文件中读取行后,可以立即将单词添加到地图中. arrlengths列表在这里实际上是无用的,因为它们除了临时存储之外不包含任何逻辑.您使用lengths列表只是为了存储已经添加到hm映射中的长度.通过调用hm.containsKey(s.length())可以达到相同的目的.

Secondly, you don't need any temporary data structures. You can add your words to the map right after you read the line from file. arr and lengths lists are actually useless here as they do not contain any logic except temporary storing. You're using lengths list just to store the lengths which has already been added to the hm map. The same can be reached by invoking hm.containsKey(s.length()).

以及您的代码的其他注释:

And an additional comment on your code:

    for(int x=0;x<lengths.size();x++) {
        if(s.length()==lengths.get(x))
            already=true;
    }

当您有这样一个循环时,只要只需要查找某个元素的某个条件是否为真,就无需在找到条件后继续循环.您应该在if语句中使用break关键字来终止循环块,例如

when you have a loop like this when you only need to find if some condition is true for any element you don't need to proceed looping when the condition is already found. You should use a break keyword inside your if statement to terminate the loop block, e.g.

    for(int x=0;x<lengths.size();x++) {
        if(s.length()==lengths.get(x))
            already=true;
            break; // this will terminate the loop after setting the flag to true
    }

但是正如我已经提到的,您根本不需要它.那只是出于教育目的.

But as I already mentioned you don't need it at all. That is just for educational purposes.

这篇关于根据长度将单词从文本文件分组到Arraylist的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆