【问题标题】:Grouping of words from a text file to Arraylist on the basis of length根据长度将文本文件中的单词分组到 Arraylist
【发布时间】:2016-10-01 12:57:59
【问题描述】:
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 映射到包含单词长度的哈希图中。

【问题讨论】:

    标签: java arraylist hashmap


    【解决方案1】:

    首先,当您将整行作为单词处理时,您的代码仅适用于逐行包含一个单词的文件。为了使您的代码更加通用,您必须通过将每一行拆分为单词来处理每一行:

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

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

    以及对您的代码的附加评论:

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

    当你有这样的循环时,当你只需要查找任何元素的某个条件是否为真时,你不需要在已经找到条件时继续循环。您应该在 if 语句中使用 break 关键字来终止循环块,例如

        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
        }
    

    但正如我已经提到的,您根本不需要它。这仅用于教育目的。

    【讨论】:

    • 非常有帮助我会做出改变
    【解决方案2】:

    您的方法冗长、令人困惑、难以调试,而且从我看来它的性能并不好(查看contains 方法)。检查这个:

    String[] words = {"a", "ab", "ad", "abc", "af", "b", "dsadsa", "c", "ghh", "po"};
    Map<Integer, List<String>> groupByLength =
      Arrays.stream(words).collect(Collectors.groupingBy(String::length));
    System.out.println(groupByLength);
    

    这只是一个例子,但你明白了。我有一组单词,然后我使用流和Java8 魔法将它们按长度分组在地图中(正是你想要做的)。你得到流,然后把它收集到一个地图上,按单词的长度分组,所以它会把每个 1 个字母的单词放在键 1 等下的列表中。

    您可以使用相同的方法,但您的单词在列表中,因此请记住不要在列表中使用Arrays.stream(),而只使用.stream()

    【讨论】:

      猜你喜欢
      • 2016-12-20
      • 1970-01-01
      • 1970-01-01
      • 2011-11-14
      • 1970-01-01
      • 2016-12-07
      • 2012-10-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多