Java8 Stream
foreach
foreach直接遍歷list
list.stream().forEach(System.out::println);//創(chuàng)建流,遍歷打印
foreach遍歷并去重
List<Integer> numbers = Arrays.asList(1, 5, 5, 2, 7, 8, 5); numbers.stream().distinct().forEach(System.out::println);
foreach遍歷集合中元素的某一屬性(map)
list.stream().map(User::getUsername).forEach(System.out::println);
foreach遍歷集合(排除集合中的某一元素)(filter)
list.stream().filter(User->User.getUsername()!="zhangsan1").forEach(System.out::println);
foreach遍歷集合元素中某一元素,組合成新的集合
list.stream().map(User::getUsername).collect(Collectors.toList()).forEach(System.out::println);
map 通過映射每個元素到對應的結(jié)果
list.stream().map(user->user.getId()+1);//把list中的每一個元素對應到user或User或任意的變量
filter 通過設置的條件過濾出元素
List<String> strings = Arrays.asList("abc", "cba", "", "what", "","yo", "aka"); List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());//過濾出不為空的元素
想了解更多?現(xiàn)在就開始免費體驗