java8中Stream如何使用,針對(duì)這個(gè)問(wèn)題,這篇文章詳細(xì)介紹了相對(duì)應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問(wèn)題的小伙伴找到更簡(jiǎn)單易行的方法。

創(chuàng)新互聯(lián)建站主要企業(yè)基礎(chǔ)官網(wǎng)建設(shè),電商平臺(tái)建設(shè),移動(dòng)手機(jī)平臺(tái),微信平臺(tái)小程序開(kāi)發(fā)等一系列專(zhuān)為中小企業(yè)按需策劃產(chǎn)品體系;應(yīng)對(duì)中小企業(yè)在互聯(lián)網(wǎng)運(yùn)營(yíng)的各種問(wèn)題,為中小企業(yè)在互聯(lián)網(wǎng)的運(yùn)營(yíng)中保駕護(hù)航。
java8使用stream可以方便對(duì)數(shù)據(jù)集進(jìn)行各種處理,顯得程序不是那么冗余,Stream使用一般都包含這三個(gè)步驟。
定義一個(gè)數(shù)據(jù)源
定義中間操作形成流水線(xiàn)
定義終端操作,執(zhí)行流水線(xiàn),生成計(jì)算結(jié)果
Stream.of("tony","9527","952")
.forEach(System.out::println);
int[] nums = {1, 2, 3, 4, 100, 6};
Arrays.stream(nums).sorted().forEach(System.out::println);
Files.lines(Paths.get("/Users/1120291/Desktop/test.txt"))
.forEach(System.out::println);該操作接受一個(gè)返回boolean的函數(shù),當(dāng)返回false的元素將會(huì)被排除掉
class Person{
private String name;
private Integer age;
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public void setName(String name) {
this.name = name;
}
public void setAge(Integer age) {
this.age = age;
}
public String getName() {
return name;
}
public Integer getAge() {
return age;
}
}public static List<Person> getPersonList(){
List<Person> personList=new ArrayList<>();
for(int i=0;i<10;i++){
Person p=new Person();
p.setName("test"+i);
p.setAge(new Random().nextInt(50));
personList.add(p);
}
return personList;
}// filter過(guò)濾數(shù)據(jù)
List<Person> personList1 = getPersonList().stream().filter(person -> person.getAge() > 25)
.collect(Collectors.toList());
personList1.stream().forEach(person -> {
System.out.println(person);
});去重操作
List<Integer> data = Stream.of(1, 7, 3, 8, 2, 4, 9, 7, 9) .distinct() .collect(Collectors.toList());
該方法限制流只返回指定個(gè)數(shù)的元素,類(lèi)似于sql中的limit
List<Integer> data = Stream.of(1, 7, 3, 8, 2, 4, 9, 7, 9) .limit(2) .collect(Collectors.toList());
扔掉前指定個(gè)數(shù)的元素,配合limit使用可以達(dá)到翻頁(yè)的效果
List<Integer> data = Stream.of(1, 7, 3, 8, 2, 4, 9, 7, 9) .skip(3) .limit(2) .collect(Collectors.toList());
流中的每個(gè)元素都會(huì)應(yīng)用到這個(gè)函數(shù)上,返回的結(jié)果將形成新類(lèi)型的流繼續(xù)后續(xù)操作,類(lèi)似于scala的map
getPersonList().stream()
.filter(customer -> customer.getAge() > 20)
.map(person -> {
return person.getName();
})
.forEach(System.out::println);在調(diào)用map之前流的類(lèi)型是Stream<Person>,執(zhí)行完map之后的類(lèi)型是Stream<String>
flatMap類(lèi)似于map,只不過(guò)是一對(duì)多,進(jìn)來(lái)一條返回多條。
getPersonList().stream().flatMap(person -> {
return Stream.of(person.getName().split(","));
}).forEach(System.out::println);//注意flatMap的返回類(lèi)型要是Stream的 flatMap(Function<? super T, ? extends Stream<? extends R>> mapper)
對(duì)所有的元素進(jìn)行排序
List<Integer> numbers = Arrays.asList(1, 7, 3, 8, 2, 4, 9); numbers.stream().sorted(Integer::compareTo).forEach(System.out::println);
終端操作會(huì)執(zhí)行所有的中間操作生成執(zhí)行的結(jié)果,執(zhí)行的結(jié)果不在是一個(gè)流。
如果流中有一個(gè)元素滿(mǎn)足條件將返回true
if (getPersonList().stream().anyMatch(person -> "test3".equals(person.getName()))) {
System.out.println("test3");
}確保流中所有的元素都能滿(mǎn)足
if (allCustomers.stream().allMatch(customer -> customer.getAge() > 20)) {
System.out.println("所有用戶(hù)年齡都大于20");
}與allMatch操作相反,確保流中所有的元素都不滿(mǎn)足
if (getPersonList().stream().noneMatch(person -> person.getAge()>50)) {
System.out.println("test3");
}返回流中的任意一個(gè)元素,比如返回大于20歲的任意一個(gè)人
Optional<Person> optional = getPersonList().stream() .filter(person -> person.getAge() > 20) .findAny(); System.out.println(optional.get());
返回流中的第一個(gè)元素
Optional<Person> optional = getPersonList().stream() .filter(person -> person.getAge() > 20) .findFirst(); System.out.println(optional.get());
接受兩個(gè)參數(shù):一個(gè)初始值,一個(gè)BinaryOperator accumulator將兩個(gè)元素合并成一個(gè)新的值 比如我們對(duì)一個(gè)數(shù)字list累加
List<Integer> numbers = Arrays.asList(1, 7, 3, 8, 2, 4, 9); Integer sum = numbers.stream().reduce(0, (a, b) -> a + b); System.out.println(sum);
找出流中的最大值、最小值 min、max
numbers.stream().reduce(Integer::max) numbers.stream().reduce(Integer::min)
統(tǒng)計(jì)流中元素的個(gè)數(shù)
numbers.stream().count()
在Java8中已經(jīng)預(yù)定義了很多收集器,我們可以直接使用,所有的收集器都定義在了Collectors中,基本上可以把這些方法分為三類(lèi):
將元素歸約和匯總成一個(gè)值
分組
分區(qū)
1.找出年齡最小和最大的人
List<Person> personList = getPersonList(); // 找出年齡最大和最小的客戶(hù) Optional<Person> min = personList.stream().collect(Collectors.minBy(Comparator.comparing(Person::getAge))); System.out.println(min); Optional<Person> max = personList.stream().collect(Collectors.maxBy(Comparator.comparing(Person::getAge))); System.out.println(max);
2.求平均年齡
List<Person> personList = getPersonList(); Double min = personList.stream().collect(Collectors.averagingInt(Person::getAge)); System.out.println(min);
3.進(jìn)行字符串的拼接
List<Person> personList = getPersonList();
// 找出年齡最大和最小的客戶(hù)
String collect = personList.stream().map(Person::getName).collect(Collectors.joining(","));
System.out.println(collect);1.根據(jù)用戶(hù)的年齡進(jìn)行分組
List<Person> personList = getPersonList(); Map<Integer, List<Person>> groupByAge = personList.stream().collect(Collectors.groupingBy(Person::getAge));
2.Map的key就是分組的值年齡,List<Person>就是相同年齡的用戶(hù)
List<Person> personList = getPersonList(); // 兩層分組 先安裝年齡分組,在按照名稱(chēng)分組 Map<String, Map<Integer, List<Person>>> groups = personList.stream() .collect(Collectors.groupingBy(Person::getName, Collectors.groupingBy(Person::getAge)));
在相對(duì)于普通的分組,這里多傳了第二個(gè)參數(shù)又是一個(gè)groupingBy;理論上我們可以通過(guò)這個(gè)方式擴(kuò)展到n層分組
3.分組后統(tǒng)計(jì)個(gè)數(shù)
List<Person> personList = getPersonList(); Map<Integer, Long> groupByCounting = personList.stream() .collect(Collectors.groupingBy(Person::getAge, Collectors.counting()));
4.以用戶(hù)所在地區(qū)分組后找出年齡最大的用戶(hù)
List<Person> personList = getPersonList(); Map<String, Optional<Person>> optionalMap = personList.stream() .collect(Collectors.groupingBy(Person::getName, Collectors.maxBy(Comparator.comparing(Person::getAge))));
關(guān)于java8中Stream如何使用問(wèn)題的解答就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,如果你還有很多疑惑沒(méi)有解開(kāi),可以關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道了解更多相關(guān)知識(shí)。
網(wǎng)頁(yè)標(biāo)題:java8中Stream如何使用
本文地址:http://www.chinadenli.net/article16/peeggg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站導(dǎo)航、ChatGPT、網(wǎng)站改版、定制網(wǎng)站、網(wǎng)站策劃、網(wǎng)站制作
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話(huà):028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)