[英]Converting from String[] to Arraylist, removing elements and converting and back to String[]
String [] TxtStr = new String[] {"bob","alan", "sam"};
List<String> stringList = new ArrayList<String>(Arrays.asList(TxtStr));
String [] TxtStr2 = new String[] {"bob","alan"};
List<String> stringList2 = new ArrayList<String>(Arrays.asList(TxtStr));
stringList.removeAll(stringList2);
String[] bTxtStr = stringList.toArray(new String[stringList.size()]);
String output = "nnn";
for (int x=0; x<bTxtStr.length; x++){
output +=bTxtStr[x];
}
Currently this is a small segment of an android project I'm working on where I have to compare the contents of 2 String[]. 目前,这是我正在处理的Android项目的一小部分,我必须在其中比较2 String []的内容。
I've been having quite a few problems so I've started out with a simple case of 2 String[] with 2 and 3 elements respectively. 我遇到了很多问题,所以我以一个简单的案例2 String []开始,分别包含2个元素和3个元素。 After initializing the String[] I convert them to ArrayLists and perform the removeAll function, which ideally should remove the elements "bob" and "alan" from the first list and eventually the output.
在初始化String []之后,我将它们转换为ArrayLists并执行removeAll函数,理想情况下,该函数应从第一个列表中删除元素“ bob”和“ alan”,并最终删除输出。
BTW using remove to stringList.remove("bob") works in terms of eliminating that particular string from the ArrayList. BTW使用remove到stringList.remove(“ bob”)的工作方式是从ArrayList中消除该特定字符串。 Just wondering what I can do to ensure that stringList.removeAll(....) works.
只是想知道我能做些什么来确保stringList.removeAll(....)工作。
Thanks for any help in advance. 感谢您的任何帮助。
you have bug in: 您有以下错误:
List<String> stringList2 = new ArrayList<String>(Arrays.asList(TxtStr));
you should use TxtStr2
: 您应该使用
TxtStr2
:
List<String> stringList2 = new ArrayList<String>(Arrays.asList(TxtStr2));
List<String> stringList = Arrays.asList("bob","alan", "sam");
List<String> stringList2 = Arrays.asList("bob","alan");
String mergedString = stringList.stream().filter(string ->!stringList2.contains(string)).collect(Collectors.joining(","));
System.out.println("Merged String: " + mergedString);
You might be ending up removing everything, because of your list creation which are based on same arrays. 您可能最终将删除所有内容,因为您的列表创建基于相同的数组。 Change
更改
List<String> stringList2 = new ArrayList<String>(Arrays.asList(TxtStr);
to 至
List<String> stringList2 = new ArrayList<String>(Arrays.asList(TxtStr2);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.