user1792440
user1792440

Reputation: 91

Print one value after split (java)

This is the code:

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

This will print all values when i use splitSell[0] :

hello 
hello 
hello 

how can i print only one value ?

Upvotes: 0

Views: 1590

Answers (2)

Snowy Coder Girl
Snowy Coder Girl

Reputation: 5518

Not sure exactly what you want. But here are some options.

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

Note that the add method only adds the element if it is not already in the Set. See the Set documentation.

Upvotes: 0

PermGenError
PermGenError

Reputation: 46428

If you meant, you want to remove the duplicate elements after the splits. add the splitted elements into an Set implementing classes and iterate over it.

 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 implementing classes dont accept duplicate elements, thus in your example would only print "hello" once.

Upvotes: 1

Related Questions