字符串列表比较器 [英] Comparator for String List

查看:103
本文介绍了字符串列表比较器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java的新手:)

I am brand new to Java :)

我有2个String列表,我想知道比较这两者的最有效方法是什么,并得到一个包含另一个字符串的结果数组.例如,我有一个名为oldStrings的列表和一个名为Strings的列表.我已经看过Comparator函数,但是还不完全了解它的工作原理,现在我想我可以创建一个for循环,遍历每个字符串,然后保存该字符串:

I have 2 String lists and I was wondering what would be the most efficient way to compare the two and have a resulting array which contains strings that are not in the other. For example, I have a list called oldStrings and one called Strings. I have seen the Comparator function but don't fully understand how it works, right now I was thinking I could create a for loop, loop through each string and then save that string:

for (final String str : oldStrings) {
  if(!strings.contains(str))
  {                     
    getLogger().info(str + " is not in strings list ");
  }
}

此列表中最多包含200个字符串.这将是解决此问题的最佳方法吗?谢谢!

There's going to be up to 200 strings in this list. Would this be the best way to go about this? Thank you!

推荐答案

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);  

更新: 更复杂的代码版本

Update: More sophisticated version of code

Collection<String> firstList = new ArrayList<String>();
firstList.add("str1");
firstList.add("str2");

Collection<String> secondList = new ArrayList<String>();
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);  

更新:

要获取两个字符串列表之间的准确差异,请这样做.

To Get acctual difference between both String list go for this.

    Set<String> setOne = new HashSet<String>();        
    Set<String> setTwo = new HashSet<String>();
    setOne.add("1");
    setOne.add("2");
    setOne.add("5");
    setTwo.add("1");
    setTwo.add("3");
    setTwo.add("4");
    Set<String> setTwoDummy = new HashSet<String>(setTwo);
    setTwo.retainAll(setOne);        
    setTwoDummy.addAll(setOne);
    setTwoDummy.removeAll(setTwo);
    System.out.println(""+setTwoDummy);

这篇关于字符串列表比较器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆