2014-09-06 28 views
0

我有两个堆栈; Stack<String> fileStack<String[]>author。他们有一个一对一的关系,即如何从两个堆栈创建一对,以一种聪明的方式

file   author 

file1  author3, author2 // file1 is written by author3 and author2 
file2  author1, author2 // file2 is written by author1 and author2 

我试图创建新的数据结构,(我虽然地图是最好的),以包含对所有信息。例如;

new data structure 

author1, file2 
author2, file1, file2 
author3, file1 

要创建此一对中,我使用HashMap<String, Set<String> allInfo,并且如实施concatanation;

int len = author.size(); 

    for(int i = 0 ; i <len ; i ++){ 
     String []temp = author.pop(); 
     int len2 = temp.length(); 

     for(int j = 0 ; j <len2 ; j ++){ 
      if(allInfo.contains(temp[j]) == false){ 
       Set<String> list = new HashSet<String>(); 
       allInfo.put(temp[j], list); 
      } 

      Set<String> temp2 = allInfo.get(temp[j]); 
      temp2.add(file.pop()); 
     } 
    } 

但是,看起来这个实现太难看了。我怎样才能更巧妙地创造这一对? (依靠内置的Java方法是首选。)

+0

解释,为什么downvote – Hevan 2014-09-06 14:06:50

回答

2

下面的代码只是更好一点。有(非JDK)库提供了一个名为multimap的数据结构,这更方便。但是你坚持使用这两个堆栈,并且关联的顺序相反,所以你需要一点编码工作。

while(! author.empty()){ 
    String f = file.pop(); // Note that in your code this is in the wrong place 
    for(String aut: author.pop()){ 
    Set<String> files = allInfo.get(aut); 
    if(files == null){ 
     files = new HashSet<>(); 
     allInfo.put(aut, files); 
    } 
    files.add(f); 
    } 
} 
0

如何为您的问题定制类型?

public class AuthorPublication{ 

private String authorName; 

private Set<String> files; 

//setters and getters 

} 
+0

请解释这是如何改善的?它不避免使用“Map ”。基本上,'Map.Entry >'是你的建议,那么是什么? – laune 2014-09-06 14:23:21

相关问题