首页
学习
活动
专区
圈层
工具
发布

Java集合
EN

Stack Overflow用户
提问于 2016-02-09 23:13:06
回答 1查看 164关注 0票数 0

我要解决这个任务。我想知道在这个case...Also中最好使用什么集合,我很想放弃集合,去找一个类来保存列表。请告诉我如何处理这件事。

代码语言:javascript
复制
Read a file (name passed in as 1st argument to program)
>
>Each line of the file has a category, a space, and a sub-category (sub-category can have whitespace within it)
>
>Want to:
>
> - Only process the pair (category, sub-category) once
>   - If a pair appears twice, ignore the second one
> - Keep track of the order of the first occurrence of each pair
> - Keep track of the count for each category
> - Legal category values are: PERSON PLACE ANIMAL COMPUTER OTHER
>   - Illegal category values should be ignored
>
>Output is:
>
>     CATEGORY     COUNT
>     PERSON
>     PLACE
>     ANIMAL
>     COMPUTER
>     OTHER
>
>Ordered list of input
>
> - Category output should be in the order shown
> - If there are no items in the file for a specified category, it should be shown with a count of 0
>
>Please follow good software engineering practices.  In addition to a working program, unit tests should be produced.
>
>Example:
>input file:
>
>     PERSON Bob Jones
>     PLACE Washington
>     PERSON Mary
>     COMPUTER Mac
>     PERSON Bob Jones
>     OTHER Tree
>     ANIMAL Dog
>     PLACE Texas
>     FOOD Steak
>     ANIMAL Cat
>
>output:
>
>     CATEGORY     COUNT
>     PERSON       2
>     PLACE        2
>     ANIMAL       2
>     COMPUTER     1
>     OTHER        1
> 
>     PERSON Bob Jones
>     PLACE Washington
>     PERSON Mary
>     COMPUTER Mac
>     OTHER Tree
>     ANIMAL Dog
>     PLACE Texas
>     ANIMAL Cat
>

这就是我目前所拥有的..。然而,hashmap正在被覆盖,我相信这是意料之中的。鲍勃琼斯读第一行后由玛丽代替。我想知道LinkedHashMap是否能够解决这个问题,或者我需要一个不同的集合。谢谢!

代码语言:javascript
复制
public void printOutput(String fileName){
  String category = null;
  String [] legalCategory ={"PERSON", "PLACE", "ANIMAL", "COMPUTER", "OTHER"};
  List<String> mapList = new ArrayList<String>();
  Map<String, String> categoryMap = new LinkedHashMap<String, String>();


  try(BufferedReader br = new BufferedReader(new FileReader(fileName))) {
      StringBuilder sb = new StringBuilder();
      String line = null;

      line = br.readLine();
      sb.append(line);
      sb.append(System.lineSeparator());

      while (line != null) {                              
          StringTokenizer st = new StringTokenizer(line);
               while (st.hasMoreElements()) {
                      category = st.nextToken();
                      for (String element : legalCategory) {
                          if (category.equalsIgnoreCase(element)) {
                             categoryMap.put(category, line.substring(category.length(), line.length()));                                   
                             break;
                          }
                      }

               }            
               line = br.readLine();
      }

      String everything = sb.toString();
  }
  catch(Exception e){
         e.printStackTrace();
  }

===========================================================================

这是完整的程序。穆罕默德的回答很有帮助!

代码语言:javascript
复制
public void printOutput(String fileName){
              String category = null;
              String [] legalCategory ={"PERSON", "PLACE", "ANIMAL", "COMPUTER", "OTHER"};
              List<String> mapList = new ArrayList<String>();
              Map<String, String> categoryMap = new LinkedHashMap<String, String>();
              List<Category> categoryList = new ArrayList<Category>();
              boolean keyFound = false;

              try(BufferedReader br = new BufferedReader(new FileReader(fileName))) {
                  StringBuilder sb = new StringBuilder();
                  String line = null;

                  line = br.readLine();
                  sb.append(line);
                  sb.append(System.lineSeparator());

                  while (line != null) {                       
                      StringTokenizer st = new StringTokenizer(line);
                      keyFound = false;
                      for(Category indCategory:categoryList){
                            if(indCategory.getCategoryKey().equalsIgnoreCase(line))
                                         keyFound=true;
                      }                    
                           while (st.hasMoreElements()) {
                                  category = st.nextToken();
                                  for (String element : legalCategory) {
                                      if (category.equalsIgnoreCase(element)) {
                                          if(!keyFound){                                              
                                                categoryList.add(new Category(line, category, line.substring(category.length(), line.length())));
                                         //categoryMap.put(category, line.substring(category.length(), line.length()));                                   
                                                break;
                                          }
                                      }
                                  }

                           }            
                           line = br.readLine();
                  }

                  String everything = sb.toString();

                  for(Category indCategory:categoryList){                  
                     System.out.println(indCategory.getCategoryItem() + "   " + indCategory.getCategorySubItem());              
               }


                 int occurrences = 0;
                 System.out.println("Category" + "\t" +    "Count" ); 
                 for(String categoryItem:legalCategory){
                        occurrences = 0;
                        for(Category indCategory:categoryList){                   
                            //System.out.println(indCategory.getCategoryItem() + "   " + indCategory.getCategorySubItem());
                            if(categoryItem.equalsIgnoreCase(indCategory.getCategoryItem()))
                                   occurrences +=1;
                      }                    
                        System.out.println(categoryItem + "\t" +   occurrences );
                 }

                // System.out.println("PERSON" + "\t" +    Collections.frequency(categoryList, "PERSON") + categoryList.size() );

              }
              catch(Exception e){
                     e.printStackTrace();
              }
       }

       public class Category{

              String categoryKey;
              String categoryItem;
              String categorySubItem;
              String occurrence;

              public Category(String categoryKey, String categoryItem, String categorySubItem){
                     this.categoryKey = categoryKey;
                     this.categoryItem = categoryItem;
                     this.categorySubItem = categorySubItem;
              }
              /**
              * @return the categoryKey
              */
              public String getCategoryKey() {
                     return categoryKey;
              }
              /**
              * @param categoryKey the categoryKey to set
              */
              public void setCategoryKey(String categoryKey) {
                     this.categoryKey = categoryKey;
              }
              /**
              * @return the categoryItem
              */
              public String getCategoryItem() {
                     return categoryItem;
              }
              /**
              * @param categoryItem the categoryItem to set
              */
              public void setCategoryItem(String categoryItem) {
                     this.categoryItem = categoryItem;
              }
              /**
              * @return the categorySubItem
              */
              public String getCategorySubItem() {
                     return categorySubItem;
              }
              /**
              * @param categorySubItem the categorySubItem to set
              */
              public void setCategorySubItem(String categorySubItem) {
                     this.categorySubItem = categorySubItem;
              }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-02-09 23:41:20

在我看来,你似乎没有考虑到子类别。这意味着每次主类别重复时,您的地图条目都会崩溃,即使它带有不同的子类别。

我建议如下:首先,您的Map键应该类似于Category+“-”+子类别,第二,创建一个模型对象(Pojo)来跟踪所有内容(包括该元素及其第一个索引的信誉计数)。阅读整行,检查category+sub类别组合是否作为键存在。如果是的话,那么获取现有的条目并更新其出现的次数。否则,填充模型类的新实例并将其添加到映射中。

如果你需要进一步澄清,请告诉我。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35304055

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档