• Post Reply Bookmark Topic Watch Topic
  • New Topic

indexing arrays  RSS feed

 
Ranch Hand
Posts: 291
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
is there a way to index an array for multiple data

say if a have an array
friesland,jersey,angus,longhorn,hereford etc etc

is there a way within printing an array to print out 0 to 2 or  to 3 etc

i did see there is a way using Arrays.toString but this prints brackets and commas....is there another way to do this?

thanks
 
Saloon Keeper
Posts: 3329
46
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To have more control as to how an array of Strings gets printed, check out
String.join()
 
Rancher
Posts: 2240
28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Use a for loop to access the elements you want, concatenate them to a String and print the String.
 
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In Java8 try:-The import of line 1 shou‍ld be obvious. Remember that println can take absolutely anything, including null, as an argument.
The method called in line 2 creates a Stream<String> from the array, but nothing will happen until the last line is executed because Streams use lazy execution.
The skip() call in line 3 limits the Stream by creating a second Stream<String> minus the first three elements of the original Stream.
The limit call in line 4 creates a third Stresm<String> but now not containing more than 5 elements.
You can reduce the Stream to something else with the collect method, but that requires a Collector object. Probably the easiest way to create a Collector object is with one of the methods of the Collectors class; the joining() method returns a Collector which can join any CharSequence object to the argument (here " " or one space). So it will join five of your cow names with single spaces in between. If you look closely at the documentation for String, you will find it implements CharSequence, so it is a suitable argument for the Collector.

Close examination of the Arrays class will reveal alternative methods for getting that Stream. Some a lot more elegant than what I showed. I managed to run the code I showed just about unchanged:-
java CowNames Friesian Highland Shorthorn Longhorn Zebu Jersey Guernsey Alderney Charolais Hereford
Longhorn Zebu Jersey Guernsey Alderney
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!