java - 如何构建一个数组并将其与另一个数组进行比较?

标签 java arrays list comparison iteration

我有一个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/

相关文章:

python - 更改范围之外的列表

java - Spring JDBC如何在不使用JTA的情况下使用事务管理器实现多数据源

java - 如何处理字符串数组的别名

php - 根据列名将查询拆分为多个数组

java - 使用链接列表的学生数据库

Java,从文件中读取对象并将它们添加到数组列表中

java - JRE 8 与 weblogic 10.3.6 (11g

java - 集合未充满 OneToMany 关系 - EclipseLink

java - 如何防止 "Scheduling restart of crashed service"?

c++ - C++ 中的位数组