JAVA:lambda example (2)
Rojer.2017.10.05
先前寫的 文章 lambda example 是針對 String 來處理的,以下繼續補充對於 class 要如何處理。
測試格式
public class Item { public String ItemName; public String ItemNo; public String ItemSource; public Integer Total; }
初始化
static private List<Item> init(){ List<Item> list = new ArrayList<Item>(); Item it = new Item("Name2","No2","E",25); list.add(it); it = new Item("Name2","No1","D",20); list.add(it); it = new Item("Name1","No2","C",15); list.add(it); it = new Item("Name1","No1","B",5); list.add(it); it = new Item("Name1","No1","A",10); list.add(it); return list; }
Count
static private void SelectCount(){
List<Item> list = init();
long count = list.stream().count();
System.out.println("count=" + count);
}
Sum
static private void Sum(){
List<Item> list = init();
int sum = list.stream().filter(x->x.getItemName().equals("Name1")).mapToInt(x->x.getTotal()).sum();
System.out.println("sum=" + sum);
}
Order by Then By
static private void orderByThenBy(){
List<Item> list = init();
list.sort(Comparator.comparing(Item::getItemName).thenComparing(Item::getItemNo).thenComparing(Item::getTotal));
for (Item it : list) {
System.out.println(it.getItemName() + "," + it.getItemNo() + "," + it.getItemSource() + "," + it.getTotal());
}
}
Order by Desc
static private void orderByDesc(){
List<Item> list = init();
list.sort(Comparator.comparing(Item::getTotal).reversed());
for (Item it : list) {
System.out.println(it.getItemName() + "," + it.getItemNo() + "," + it.getItemSource() + "," + it.getTotal());
}
}
只查詢單一欄位
static private void selectSingleColumn(){
List<Item> list = init();
List<String> itemSourceList = list.stream().map(x->x.getItemName()).collect(Collectors.toList());
for (String it : itemSourceList) {
System.out.println(it);
}
}
查詢單一欄位並過濾重複欄位
static private void selectDistinct(){
List<Item> list = init();
List<String> itemSourceList = list.stream().map(x->x.getItemName()).distinct().collect(Collectors.toList());
for (String it : itemSourceList) {
System.out.println(it);
}
}
Select New Object
static private void selectNew(){
List<Item> list = init();
List<String[]> newlist = list.stream()
.map(x-> new String[] { x.ItemName , x.ItemNo }).collect(Collectors.toList());
for(String[] it: newlist){
System.out.println(it[0] + "," + it[1]);
}
}
0 意見:
張貼留言