3

I'm having trouble figuring out how to apply a math operation to each item of an ArrayList. The ArrayList will be user inputted so there's no telling how many items would be within it. Is there a method that might aid in doing this?

2 Answers2

1

Use ListIterator -> https://docs.oracle.com/javase/7/docs/api/java /util/ListIterator.html

Unlike plain Iterator, ListIterator will allow you to store newly computed value back to the list

ArrayList<Integer> source = ...

ListIterator<Integer> iter = source.listIterator();

while( iter.hasNext() )
{
  Integer value = iter.next();

  Integer newValue = Integer.valueOf( value.intValue() * 2 );

  iter.set(newValue);
}
Alexander Pogrebnyak
  • 44,836
  • 10
  • 105
  • 121
0

as @puhlen says, in java 8, use stream and lambda expression

List liste = new ArrayList<>();
liste.stream().forEach(o->{
    //apply your math on o
});

stream provides you many other functionnalities to filter, order, collect... use it if you're on java8

or as @neil-locketz says in java before 8 use a foreach loop

 List<type> liste = new ArrayList<>();
for(type o : liste){
    //math on object o here
}
Tokazio
  • 516
  • 2
  • 18
  • Actually, that code won't do anything whatsoever. – Bohemian Sep 28 '16 at 20:50
  • 1
    Your stream code does nothing because there is no terminating method. That is, `map()` isn't called until the terminating method (eg `collect()`, `reduce()` etc) requests the next element. With no terminating method, literally no code will fire. – Bohemian Sep 28 '16 at 20:56
  • sorry, i think forEach and i write map... edited – Tokazio Sep 28 '16 at 21:24