在C#中,微軟基於IEnumerable接口,提供許多便捷的擴展方法,便於實際的開發。在Java 1.8中,Collection
一、外部迭代
- 首先調用iterator方法,產生一個新的Iterator對象,進而控制整個迭代過程。(迭代過程通過顯示調用Iterator對象的hasNext和next方法完成迭代)
public static void main(String[] args) {
Collection<String> list = new ArrayList<>();
list.add("Android");
list.add("iPhone");
list.add("Windows Mobile");
Iterator<String> itr = list.iterator();
while (itr.hasNext()) {
String lang = itr.next();
System.out.println(lang);
}
}
二、內部迭代
是基於stream使用函數式編程的方式在集合上進行復雜的操作。(類似於C#基於IEnumerable的擴展方法,eg:Where()方法)
在函數式編程中,將函數作為參數來傳遞,傳遞過程中不會執行函數內部耗時的計算,直到需要這個結果的時候才調用,這樣就可以避免一些不必要的計算而改進性能。
在Java的stream()方法中,有惰性求值方法與及早求值方法
返回值為Stream為惰性求職方法。
返回值為空或者別的值為及早求職方法
三、常用的Stream API(相當於IEnumerable的擴展方法表)
示例代碼的基礎代碼
public class Artist {
private String name;
private int age;
public Artist() {
}
public Artist(String n, int a) {
this.name = n;
this.age = a;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public List<Artist> getArtists() {
List<Artist> artists = new ArrayList<Artist>();
artists.add(new Artist("lily", 20));
artists.add(new Artist("Lucy", 21));
artists.add(new Artist("jack", 19));
return artists;
}
}
1.collect(Collectors.toList())
- 該方法就是將Stream生成一個列表,相當於C#的ToList()
List<String> collected = Stream.of("a", "b").collect(Collectors.toList());
Set<String> names=new HashSet<>();
names=artists.stream().map(u->u.getName()).collect(Collectors.toSet());
2.map
- 將一種類型的值轉換為另外一種類型的值。
- 代碼:將List
轉換成List
List<String> collected = Stream.of("a", "b").collect(Collectors.toList());
List<Integer> figure = collected.stream().map(s -> {
Integer i;
switch (s) {
case "a":
i = 1;
break;
case "b":
i = 2;
break;
default:
i = -1;
break;
}
return i;
}).collect(Collectors.toList());
3.filter(類似於C#的Where)
- 遍歷數據並檢查其中的元素是否符合給出的表達式的元素
4.flatMap(類似C# AddRange)
- 將多個Stream連接成一個Stream,這時候不是用新值取代Stream的值,與map有所區別,這是重新生成一個Stream對象取而代之。
List<Integer> a=new ArrayList<>();
a.add(1);
a.add(2);
List<Integer> b=new ArrayList<>();
b.add(3);
b.add(4);
List<Integer> figures=Stream.of(a,b).flatMap(u->u.stream()).collect(Collectors.toList());
figures.forEach(f->System.out.println(f));
5.max及min
- 求最大值和最小值
- 此時max及min接受的是Comparator<? super T> comparator
Integer m=figures.stream().max(Comparator.comparing(u->u)).get();
System.out.println(m);
6.reduce
- 從一組值中生成一個值。比如在一組List
將所有元素依次相加
Integer s = figures.stream().reduce((x, y) -> x + y).get();
四、總結
- 1.在編寫項目代碼時候,多使用內部迭代,避免太多的外部冗余,簡化代碼
- 2.將Lambda表達式與Stream方法結合起來,可以完成很多操作