How can I get only specific values from an Arraylist

nani10 :

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));
}
Stephen C :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=87592&siteId=1