Java 如何以巧妙的方式从两个堆栈创建一对

Java 如何以巧妙的方式从两个堆栈创建一对,java,Java,我有两个堆栈堆栈文件和堆栈作者。他们有一对一的关系,即 file author file1 author3, author2 // file1 is written by author3 and author2 file2 author1, author2 // file2 is written by author1 and author2 我已经尝试创建新的数据结构(我认为Map是最好的)来包含成对的所有信息。比如, new d

我有两个堆栈<代码>堆栈文件和
堆栈作者
。他们有一对一的关系,即

file            author

file1        author3, author2    // file1 is written by author3 and author2
file2        author1, author2    // file2 is written by author1 and author2
我已经尝试创建新的数据结构(我认为Map是最好的)来包含成对的所有信息。比如,

new data structure

author1, file2
author2, file1, file2
author3, file1

为了创建这一对,我使用了
HashMap下面的代码只是稍微好一点。有一些(非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 );
  }
}
while(!author.empty()){
字符串f=file.pop();//请注意,在您的代码中,这是在错误的位置
for(字符串aut:author.pop()){
Set files=allInfo.get(aut);
if(files==null){
files=newhashset();
allInfo.put(aut,文件);
}
添加(f);
}
}

为您的问题定制一个自定义类型怎么样

public class AuthorPublication{

private String authorName;

private Set<String> files;

//setters and getters

}
公共类AuthorPublication{
私有字符串authorName;
私有集合文件;
//二传手和接球手
}

解释,为什么下载请解释这是如何改进的?它不能避免使用
映射
。基本上,
Map.Entry
就是你所建议的,那又怎样?
public class AuthorPublication{

private String authorName;

private Set<String> files;

//setters and getters

}