java中List的常用功能


本文記錄一下List的常用功能和方法,用到了一些lambda表達式,使代碼看起來更簡潔。

我們先創建一個List對象names如下:

List<String> names = Arrays.asList("java", "python", "c++", "php", "c#");

遍歷

names.forEach(System.out::println);

結果:
java
python
c++
php
c#

排序

Collections.sort(names, (a, b) -> a.compareTo(b));
names.forEach(System.out::println);

結果:
c#
c++
java
php
python

過濾(單個條件)

Predicate<String> p1 = (n) -> n.startsWith("c");
Predicate<String> p2 = (n) -> n.length() == 3;
names.stream().filter(p1).forEach("c開頭的:" + System.out::println);
names.stream().filter(p2).forEach("長度爲3的:" + System.out::println);

結果:
c開頭的:c#
c開頭的:c++
長度爲3的:c++
長度爲3的:php

過濾(多個條件)

這裏用上一條的結果p1、p2做運算

names.stream().filter(p1.and(p2)).forEach("與:\n" + System.out::println);
names.stream().filter(p1.or(p2)).forEach("或:\n" + System.out::println);

結果:
與:
c++
或:
c#
c++
php

map()統一對元素進行操作

names.stream().map(n -> n + " is good!").forEach(System.out::println);

結果:
c# is good!
c++ is good!
java is good!
php is good!
python is good!

連接

System.out.println(names.stream().map(n -> n.toUpperCase()).collect(Collectors.joining(",")));

結果:
C#,C++,JAVA,PHP,PYTHON

去重

List<String> names1 = Arrays.asList("java", "python", "c++", "php", "c#", "c++");
names1 = names1.stream().filter(n -> n.startsWith("c")).distinct().collect(Collectors.toList());
System.out.println(names1);

結果:
[c++, c#]

計算

List<Double> doubleList = Arrays.asList(2.0,6.0,4.0,7.0,1.0,9.0);
DoubleSummaryStatistics res = doubleList.stream().mapToDouble(n -> n).summaryStatistics();
System.out.println("ave:"+res.getAverage()+"\tmax:"+res.getMax()+"\tsum:"+res.getSum());

結果:
ave:4.833333333333333 max:9.0 sum:29.0

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章