Sorry, i need to clarify detailly.
I'm using Java to write simple array
recording 3 times stock buying; every new car initiated is presented as new transaction made:
~~ 1 share purchased at time $100/share.
2 shares are purchased at time $200/share.
3 shares are purchased at time $300/share.
Total 6 shares in hand. ~~
How to calculate the average buying price per share ? Which continually run by keep adding new car.
package javaex;
import java.util.ArrayList;
import java.util.function.Predicate;
public class javaExstockprice
public static void main(String[] args){
ArrayList<Car> al= new ArrayList();
al.add(new Car(1,100));
al.add(new Car(2,200));
al.add(new Car(3,300));
System.out.println("showsharesbuyingmethod-alltransaction = shares : buying");
al.forEach(c->c.showsharesbuying() );
System.out.println();
al.removeIf(c->c.shares>1);
System.out.print("transcation amount 1 share / below");
System.out.println();
al.forEach(c->c.showsharesbuying() );
System.out.println();
}
class Car
float shares;
float buying;
Car (float a, float b) {
shares = a;
buying = b;
}
void showsharesbuying() {
System.out.println("showsharesbuying " + shares+ " : " + buying);
}
Well, trying to guess what you want, here is what comes to my mind:
import java.util.List;
import java.util.ArrayList;
import java.util.function.Predicate;
public class JavaExStockPrice {
public static void main(String[] args){
List<Car> al= new ArrayList();
al.add(new Car(1,100));
al.add(new Car(2,200));
al.add(new Car(3,300));
System.out.println("showsharesbuyingmethod-alltransaction = shares : buying");
al.forEach(c->c.showSharesBuying() );
System.out.println("Avg: " + priceAvg(al));
System.out.println();
al.removeIf(c->c.shares>1);
System.out.print("transcation amount 1 share / below");
System.out.println();
al.forEach(c->c.showSharesBuying() );
System.out.println("Avg: " + priceAvg(al));
System.out.println();
}
static double priceAvg(List<Car> l) {
return l.stream().mapToDouble(c -> c.buying * c.shares).average().getAsDouble() /
l.stream().mapToDouble(c -> c.shares).average().getAsDouble();
}
}
class Car {
float shares;
float buying;
Car (float a, float b) {
shares = a;
buying = b;
}
void showSharesBuying() {
System.out.println("showsharesbuying " + shares+ " : " + buying);
}
}
Having logic on static methods like this is not a good idea, but I'm not sure if that's what you want to know.