我有一个ArrayList
,其中包含从数据库检索的字符串。这些字符串是博客中各个帖子的标签,例如:
video, java, php, xml,
css, java, foo, bar,
xml, php, foo, bar, dog
我正在尝试循环遍历列表。用逗号将每个字符串拆分为一个数组,并检查我的 uniqueTag 数组是否不包含拆分数组中的元素。如果没有,请将其添加到 uniqueTag 数组中。
这就是我已经走了多远:
List<String> tagList = conn.getAllTags();
String[] uniqueTags;
for(String item: tagList){
// split the row into array of comman seperated elements
String[] splitItem = item.split(",");
for(int i=-1; i<=splitItem.length; i++){
// compare this element with elements in uniqueTags
// and if it doesn't exit in uniqueTags
// add it.
}
}
如何比较和动态构建 uniqueTags 数组?
最佳答案
我会使用Set<String>
以防止重复值。
大致如下:
Set<String> uniques = new HashSet<String>();
for(String item: tagList){
// split the row into array of comman seperated elements
String[] splitItem = item.split(",");
for (String item: splitItem) {
uniques.add(item.trim()); // trimming whitespace and adding to set
...
关于java - 如何构建一个数组并将其与另一个数组进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24081184/