user2598911
user2598911

Reputation: 379

Parsing lists & strings

I am using this code and ds list prints for example:

aaa.(bbb)
aaa.(eee)
ccc.(ddd) 
...

I need it to print the strings related to aaa in the same brackets using, to separate them.

Example: aaa.(bbb,eee)

What should I change in my code?

I know the code is not complete, but it would complicate it a lot if I added everything. The goal is while iterating on templist for the string s, to add templist elements in the format mentioned.

List<String> templist = new ArrayList<String>() ;
List<String> ds = new ArrayList<String>() ;

String s = "aaa"

String selecfin = null ;

for(int j =0;j<templist.size(); j++){

       String selecP = templist.get(j);

       selecfin = s+".("+selecP+")";
       ds.add(selecfin);
}

Upvotes: 0

Views: 109

Answers (2)

An SO User
An SO User

Reputation: 25028

You can check the presence of aaa as follows:

if(selecP.contains("aaa")){
  // separate and do what you need
}  

to add templist elements in the format mentioned. I do not quite understand what that means.

Also, you can make the code a little more compact by using the for-each loop as follows:

for(String selecP : tempList){
  if(selecP.contains("aaa"){
      // something
  }
}  

You aren't adding anything to your lists in the code snippet you provided. You are iterating over empty lists.


SSCCE:
Run it here: http://ideone.com/66EIax

/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        List<String> tempList = new ArrayList<String>();
        List<String> ds = new ArrayList<String>();

        tempList.add("aaa.(bbb)");
        tempList.add("aaa.(eee)");
        tempList.add("ccc.(ddd)");

        String s = "aaa";

        for(String selecP : tempList){
            if(selecP.contains(s)){
                ds.add(new String(selecP));
            }
        }

        for(String each : ds){
            System.out.println(each);
        }
    }
}  

Output:

aaa.(bbb)
aaa.(eee)

Upvotes: 0

samvdst
samvdst

Reputation: 638

I didn't test it, but you can try it like this

List<String> templist = new ArrayList<String>() ;
List<String> ds = new ArrayList<String>() ;

String s = "aaa";

String selecfin = null ;
String tmp = null;

for(int i=0; i<templist.size(); i++) {
  if(tmp != null) {
    tmp = tmp + "," + templist.get(i);
  } else {
    tmp = templist.get(i);
  }
}

selecfin = s + ".(" + tmp + ")";

ds.add(selecfin);

Upvotes: 2

Related Questions