hbhakhra
hbhakhra

Reputation: 4236

Group strings into an array of strings

I got a quick question. I am kinda lazy in the code I write, meaning I want to minimize my typing. I just came across this problem so I am wondering if there is a solution.

I have a bunch of strings that I want to loop through. I was thinking that the best way to do this would be to put them all in an array of strings and loop through array.

My question: Is there an eclipse shortcut to do this? Also, is there a better way to loop through a bunch of string variables?

Thanks

UPDATE: Sorry, I guess I wasn't clear. I know how to do a for loop. Let me post my code:

private static final String ID = "_id";
private static final String TITLE = "title";
private static final String YEAR = "year";
private static final String DIRECTOR = "director";
private static final String BANNER = "banner_url";
private static final String TRAILER = "trailer_url";

I did this:

private static final String[] labels = {ID, TITLE, YEAR, DIRECTOR, BANNER, TRAILER};

I was looking for a way to loop through it, without putting the strings in an array.

Upvotes: 0

Views: 434

Answers (5)

erimerturk
erimerturk

Reputation: 4288

try this.

Preferences -> Java -> Editor -> Templates

you should give a keyword for example "helloworld" and define a pattern like this.

public static void helloWorld(){
   System.out.println("hello world");
}

apply settings.

and then in your class, write "helloworld" and then CTRL + SPACE, you will see your pattern.

Upvotes: 2

Dave Newton
Dave Newton

Reputation: 160251

If you type for and Ctrl-Space it'll give you the different iterations available.

To actually create the list the quickest is to use Arrays.asList:

List<String> foos = Arrays.asList("ohai", "kthxbai", "wat"); // Or...
List<String> foos = Arrays.asList(existingStringArray);

Upvotes: 1

AHungerArtist
AHungerArtist

Reputation: 9579

Allow me to rephrase part of your question: "Is there a better way to loop through something other than looping through it?" Think about that. If you have to loop, you have to loop.

  • Edited out other part since other user gave a better answer.

Upvotes: 1

mprabhat
mprabhat

Reputation: 20323

eclipse shortcut is to type foreach then CTRL+SPACE will give do the trick for you.

Upvotes: 2

Tudor
Tudor

Reputation: 62459

I don't know what you have tried so far but for me it's convenient to put them in a List with add and then loop with a "foreach" construct:

List<String> list = new ArrayList<String>();
// add some strings.
for(String s: list) {
}

Upvotes: 0

Related Questions