Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

List of Items

 
Sege Stephen
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a List that returns list of items, from the list of items returned, I want to say tell it to return just the first 4 or whatever number I set it to.

How do I do that, here is my code



System.out prints all the Items, I have other code in my class that tells it to return items that are published between 5th - 7th. And it now returns 10 items found within that date range. I want only the first 4 of the 10 items to be returned. How do I do that within my code?
 
Mark Vedder
Ranch Hand
Posts: 624
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Take a look at the subList(int fromIndex, int toIndex) method of the List interface. Is that what you want to do?
 
BV Boose
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
maybe: (add adequate checks for list size)


but since you have to access list more then once, would it make more sense to get it once as an instance variable, then access the different parts of the list as you need it?


Originally posted by Sege Stephen:
I have a List that returns list of items, from the list of items returned, I want to say tell it to return just the first 4 or whatever number I set it to.

How do I do that, here is my code



System.out prints all the Items, I have other code in my class that tells it to return items that are published between 5th - 7th. And it now returns 10 items found within that date range. I want only the first 4 of the 10 items to be returned. How do I do that within my code?
 
Mark Vedder
Ranch Hand
Posts: 624
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
p.s. When testing your code, be sure to test the case where the full list is smaller than the number of items you want. You'll need to write some code to handle that situation if you want to handle it gracefully.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic