0

这是代码:

ArrayList<String> listSell = new ArrayList<String>();

listSell.add("hello : world : one");
listSell.add("hello : world : one");
listSell.add("hello : world : one");

String splitSell[] = null;

for (int i = 0; i < listSell.size(); i++){
    splitSell = (listSell.get(i)).split(":");
    System.out.println(splitSell[0]);
}

当我使用 splitSell[0] 时,这将打印所有值:

hello 
hello 
hello 

我怎样才能只打印一个值?

4

2 回答 2

1

如果您的意思是,您想在拆分后删除重复的元素。将拆分的元素添加到 Set 实现类中并对其进行迭代。

 Set<String> set = new LinkedHashSet<>();
for (int i = 0; i < listSell.size(); i++){
    splitSell = (listSell.get(i)).split(":");
    set.add(splitSell[0]);
}

   for(String s: set){
     System.out.println(s);
     }

java.util.Set 实现类不接受重复元素,因此在您的示例中只会打印一次“hello”。

于 2012-11-08T15:28:30.260 回答
0

不确定你想要什么。但这里有一些选择。

ArrayList<String> listSell = new ArrayList<String>();

listSell.add("hello : world : one");
listSell.add("hello : world : one");
listSell.add("hello : world : one");

String splitSell[] = null;
Set<String> split1 = new TreeSet<String>();
Set<String> split2 = new TreeSet<String>();
Set<String> split3 = new TreeSet<String>();

for (String listItem : listSell) {
    splitSell = listItem .split(":");
    split1.add(splitSell[0]);
    split2.add(splitSell[1]);
    split3.add(splitSell[2]);
}

//Prints all the first values
for (String string1 : split1) {
    System.out.println(string1);
}

//Prints all the second values
for (String string2 : split2) {
    System.out.println(string2);
}

//Prints all the third values
for (String string3 : split3) {
    System.out.println(string3);
}

请注意,该add方法仅在元素不在Set. 请参阅设置文档

于 2012-11-08T17:04:53.593 回答