Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get only specific values from an Arraylist

Tags:

java

arraylist

I have an ArrayList<Integer> with values (20, 40, 60, 80, 100, 120) Is it possible to only retrieve the position 2-5 only which is 60, 80, 100 and 120? Thanks for any help.

for (DataSnapshot price : priceSnapshot.getChildren()) {
    int pr = price.getValue(Integer.class);
    priceList.add(pr); // size is 61 
}
int total = 0;
List<Integer> totalList = 
            new ArrayList<Integer>(priceList.subList(29, 34));               
for (int i = 0; i < totalList.size(); i++) {
    int to = totalList.get(i);
    total += to;
    txtPrice.setText(String.valueOf(total));
}
like image 542
nani10 Avatar asked Jun 09 '26 13:06

nani10


1 Answers

In Java you can create a sublist (javadoc) of a list; e.g.

List<Integer> list = ...
List<Integer> sublist = list.sublist(2, 6);

Notes:

  1. The the upper bound is exclusive, so that to get the list element containing 120 we must specify 6 as the upper bound, not 5.

  2. The resulting sublist is "backed" by the original list. Therefore:

    • there is no copying involved in creating the sublist, and
    • changes to the sublist will modify the corresponding positions in the original list.
like image 169
Stephen C Avatar answered Jun 12 '26 01:06

Stephen C



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!