2014年5月18日日曜日

[Java]java.util.stream

int sum = widgets.stream()
                      .filter(w -> w.getColor() == RED)
                      .mapToInt(w -> w.getWeight())
                      .sum();
こ、これは?
Java(Java Platform SE 8)なんです。

従来の書き方だとこんな感じでしょうか。
public class Widget {
    private COLOR color;
    private int weight;
    
    public enum COLOR {
        RED,
        YELLOW,
        BLUE
    }
    
    public Widget(COLOR color, int weight) {
        this.color = color;
        this.weight = weight;
    }
    
    public COLOR getColor() {
        return color;
    }
    
    public int getWeight() {
        return weight;
    }
}

List<Widget> widgets = new ArrayList<Widget>() {{
    add(new Widget(RED, 1));
    add(new Widget(RED, 2));
    add(new Widget(YELLOW, 3));
    add(new Widget(BLUE, 4));
    add(new Widget(RED, 5));
}};
Stream<Widget> stream = widgets.stream();
Predicate<Widget> predicate = new Predicate<Widget>() {
    @Override
    public boolean test(Widget w) {
        return w.getColor() == RED;
    }
};
stream = stream.filter(predicate);
ToIntFunction<Widget> tif = new ToIntFunction<Widget>() {
        @Override
        public int applyAsInt(Widget w) {
            return w.getWeight();
        }
};
IntStream is = stream.mapToInt(tif);
int sum = is.sum();
System.out.println("sum: " + sum);


-----------------------------------
Rubyで書くとこんな感じです。
class Widget
  attr_accessor :color, :weight
  def initialize(color, weight)
    @color = color
    @weight = weight
  end
end
sum = [Widget.new(:RED, 1), Widget.new(:RED, 2), Widget.new(:YELLOW, 3), Widget.new(:BLUE, 4), Widget.new(:RED, 5)].select{ |w| w.color == :RED }.inject(0){ |memo, obj| memo += obj.weight }
p sum


0 件のコメント:

コメントを投稿