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?
            Asked
            
        
        
            Active
            
        
            Viewed 2,596 times
        
    3
            
            
        - 
                    2Foreach loop? http://stackoverflow.com/questions/85190/how-does-the-java-for-each-loop-work – Neil Locketz Sep 28 '16 at 20:45
- 
                    6You can use stream().map to apply a function to each element of a List – puhlen Sep 28 '16 at 20:46
- 
                    This gives an example of using stream.map() : https://www.mkyong.com/java8/java-8-filter-a-map-examples/ – StvnBrkdll Sep 28 '16 at 20:49
- 
                    What _exactly_ do you want to do? Are the types going to be the same after calculation? Can you give an example? – Tunaki Sep 28 '16 at 21:00
2 Answers
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
- 
                    
- 
                    1Your 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
- 
                    
