字符串列表的比较器
我是Java的新手:)
我有2个字符串列表,我想知道什么是比较两者的最有效方法,并有一个结果数组,其中包含不在另一个中的字符串。 例如,我有一个名为oldStrings的列表和一个名为Strings的列表。 我已经看过Comparator函数但是没有完全理解它是如何工作的,现在我想我可以创建一个for循环,循环遍历每个字符串然后保存该字符串:
for (final String str : oldStrings) { if(!strings.contains(str)) { getLogger().info(str + " is not in strings list "); } }
此列表中最多可包含200个字符串。 这会是最好的方法吗? 谢谢!
Collection firstList = new ArrayList() {{ add("str1"); add("str2"); }}; Collection secondList = new ArrayList() {{ add("str1"); add("str3"); add("str4"); }}; System.out.println("First List: " + firstList); System.out.println("Second List: " + secondList); // Here is main part secondList.removeAll(firstList); System.out.println("Result: " + secondList);
更新:更复杂的代码版本
Collection firstList = new ArrayList (); firstList.add("str1"); firstList.add("str2"); Collection secondList = new ArrayList (); secondList.add("str1"); secondList.add("str2"); secondList.add("str3"); System.out.println("First List: " + firstList); System.out.println("Second List: " + secondList); // Here is main part secondList.removeAll(firstList);
更新:
要获得两个字符串列表之间的实际差异,请执行此操作。
Set setOne = new HashSet (); Set setTwo = new HashSet (); setOne.add("1"); setOne.add("2"); setOne.add("5"); setTwo.add("1"); setTwo.add("3"); setTwo.add("4"); Set setTwoDummy = new HashSet (setTwo); setTwo.retainAll(setOne); setTwoDummy.addAll(setOne); setTwoDummy.removeAll(setTwo); System.out.println(""+setTwoDummy);
首先,您的解决方案的问题是它只会找到oldStrings
元素而不是strings
。 如果你采用这种方法,那么你也需要在另一个列表上循环。
如果这不是作业,那么请查看Apache Commons Collections中的CollectionUtils.disjunction 。
比较两个字符串列表,并得到一个结果数组,其中包含不在另一个字符串中的字符串。
描述是不明确的,因为我们不知道我们是否只需要来自第一个列表,第二个列表或两者的非匹配字符串。 下面是两者的伪代码。
for (String str : oldStrings) { if(strings.contains(str)) { intersectionList.add(str); } } oldStrings.removeAll(intersectionList); strings.removeAll(intersectionList); result = strings.addAll(oldStrings).toArray();
要么
copyStrings = strings.clone(); strings.removeAll(oldStrings); oldStrings.removeAll(copyStrings); result = strings.addAll(oldStrings).toArray();
您应该使用Google Guava的Sets
实用程序。
Set s = Sets.newHashSet("a", "b", "c", "d"); Set t = Sets.newHashSet("f", "g", "a", "c"); Sets.SetView difference = Sets.difference(s, t); System.out.println(difference); // prints [b, d]