In MySQL you can do something like this:
select * from sometable order by id desc limit 3 offset 0;
Which would return the first 3 results. How is something like this achievable in java?
If I have an ArrayList
of an odd amount of elements:
ArrayList<String> ids = new ArrayList<String>();
ids.add("1");
ids.add("2");
ids.add("3");
ids.add("4");
ids.add("5");
ids.add("6");
ids.add("7");
ids.add("8");
ids.add("9");
ids.add("10");
ids.add("11");
How would one go about getting only 3 results from this ArrayList
for each offset (or less than 3 if there are no more elements left)?
for example, say if the limit is always 3 and offset = 0
:
it should spit out 1,2,3
if offset = 3
:
4,5,6
offset = 6
:
7,8,9
offset = 9
:
10,11
The way i'm currently doing it is by creating a subList of the list:
int endOf = offset+3;
ArrayList<String> ids2 = new ArrayList<String>(ids.subList(offset, endOf));
But it breaks when the offset is larger than the size of ids...
If this can't be done with arraylists is there a better way to do it?
EDIT:
Based on the two answers, Andy's method seemed to perform better:
long startTime = System.nanoTime();
//tried each method here
long stopTime = System.nanoTime();
System.out.println(stopTime - startTime);
Without streams:
40960
17167
13854
10240
With streams:
303584
118060
47284
40357
EDIT2:
The benchmark test above by no means should be relied on. For more info why see here: How do I write a correct micro-benchmark in Java?
Just clamp the parameters of subList
:
list.subList(
Math.min(list.size(), offset),
Math.min(list.size(), offset + limit))
If you find the syntax inconvenient, write a helper method, e.g.
<T> List<T> clampedSublist(List<T> list, int offset, int limit)