我有两个数组列表。其中一个列出了在州内出生的所有总统(名单A)。第二个列出了所有的总统(名单B)。我必须比较两者,并打印出一份并非出生在我们任何现状的总统名单。基本上,它们不在列表A中。所以我必须找到列表之间的所有共同名称,并从列表B中删除它们。我该怎么做呢?
import java.util.*;
import java.io.*;
// NO CMD ARGS - ALL FILENAMES MUST BE HARDOCDED AS I HAVE DONE FOR YOU HERE
public class Potus
{
public static void main( String[] args ) throws Exception
{
BufferedReader infile1 = new BufferedReader( new FileReader("state2Presidents.txt") );
BufferedReader infile2 = new BufferedReader( new FileReader("allPresidents.txt") );
//BufferedReader infile3 = new BufferedReader( new FileReader("allStates.txt") );
HashMap<String,ArrayList<String>> Map = new HashMap<String,ArrayList<String>>();
HashMap<String,String> Maping = new HashMap<String,String>();
ArrayList<String> inverting = new ArrayList<String>();
ArrayList<String> presState = new ArrayList<String>();
String state;
while ((infile1.ready()))
{
ArrayList<String> president = new ArrayList<String>();
state = infile1.readLine();
String [] states = state.split(" ");
for(int i=1; i<states.length; i++)
{
president.add(states[i]);
inverting.add(states[i]);
Maping.put(states[i],states[0]);
}
Map.put(states[0], president);
presState.add(states[0]);
}
Collections.sort(presState);
Collections.sort(inverting);
System.out.println( "The following states had these presidents born in them:\n"); // DO NOT REMOVE OR MODIFY
for(int i=0; i<presState.size(); i++)
{
System.out.print(presState.get(i));
ArrayList<String> value = Map.get(presState.get(i));
for (int j=0; j< value.size() ; j++)
{
System.out.print(" "+value.get(j));
}
System.out.println();
}
System.out.println( "\nList of presidents and the state each was born in:\n"); // DO NOT REMOVE OR MODIFY
for(int i=0; i<inverting.size(); i++)
{
System.out.print(inverting.get(i));
String val = Maping.get(inverting.get(i));
System.out.println(" "+val);
}
System.out.println( "\nThese presidents were born before the states were formed:\n"); // DO NOT REMOVE OR MODIFY
ArrayList<String> america = new ArrayList<String>();
ArrayList<String> am = new ArrayList<String>();
String l;
String line;
while((line = infile2.readLine()) != null)
{
america.add(line);
}
while((l = infile1.readLine()) != null)
{
for(int i=1; i<l.length();i++)
{
am.add(l);
}
}
Collections.sort(america);
Collections.sort(am);
america.removeAll(am);
}
答案 0 :(得分:1)
您可以尝试listB.removeAll(listA)
答案 1 :(得分:0)
将List
A中的所有校长放在Set
中,然后遍历List
B,检查每个项目是否属于A,如果是,请将元素的索引添加到第三个清单。之后,遍历索引列表,从List
B中删除项目。如果B中的删除为O(1),则在O(m + n)中运行。
如果列表相对较小,我会按照另一个答案的建议使用removeAll()
。
答案 2 :(得分:0)
有多种方法可以做到这一点。一,如Evgeniy Dorofeev所述,您可以使用listA.removeAll(listB);
您也可以尝试遍历ListB的所有元素(假设列表的类型为String,因为您尚未指定)
for( String s : ListA ) {
if ( ListB.contains( s ) )
ListB.remove( ListB.indexOf( s ) );
}