- カスタムオブジェクトItemのマスタリスト中から興味のある品だけを取り出し
- 更に10000円以上のものだけを選び
- かつ価格を安いものから昇順に並べる
例である.
package org.tanuneko; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class Reducer { public static void main( String args[] ) { // since this is lazy evaluation, WareHouse::findItembyId is not called for all entries in item list held by WareHouse List<Integer> interests = Arrays.asList( 1,2,3,4,5,6 ); List<Item> items = interests.stream().map(WareHouse::findItembyId) .filter((x)->x.getPrice()>10000) .sorted( (x,y)->x.getPrice() - y.getPrice() ) .collect(Collectors.toList()); items.stream().forEach(System.out::println); } } class WareHouse { static final List<Item> items = genItems(); public static Item findItembyId( int id ) { // better to use orElse() return items.stream().filter(x->x.getId()==id).findFirst().get(); } private static List<Item> genItems() { List<Item> items = new ArrayList<>(); items.add( new Item( 1, 500, "Basket" ) ); items.add( new Item( 2,1200, "Rack" ) ); items.add( new Item( 3, 700, "Small Table" ) ); items.add( new Item( 4, 50000, "Granite Table" ) ); items.add( new Item( 5, 15000, "Closet" ) ); items.add( new Item( 6, 400, "Grout" ) ); items.add( new Item( 7, 28000, "Small Couch" ) ); return items; } }Items.java
package org.tanuneko; public class Item { private int id; private int price; private String name; public Item( int id, int price, String name ) { this.id = id; this.price = price; this.name = name; } public int getId() { return id; } public int getPrice() { return price; } public String getName() { return name; } @Override public String toString() { return "Item{" + "id=" + id + ", price=" + price + ", name='" + name + '\'' + '}'; } }
Item{id=5, price=15000, name='Closet'} Item{id=4, price=50000, name='Granite Table'}
0 件のコメント:
コメントを投稿