遍歷
public static void main(String[] args) {
List<User> userList = Lists.newArrayList();
User user1 = new User(1L, "張三", 24);
User user2 = new User(2L, "李四", 27);
User user3 = new User(3L, "王五", 21);
userList.add(user1);
userList.add(user2);
userList.add(user3);
userList.stream().forEach(user ->{
System.out.println(user.getName());
});
}
List轉爲Map
常用:
public Map<Long, String> getIdNameMap(List<Account> accounts) {
return accounts.stream().collect(Collectors.toMap(Account::getId, Account::getUsername));//第一個參數爲map鍵值對中的key,第二個爲value
}
或
public Map<Long, String> getIdNameMap(List<Account> accounts) {
return accounts.stream().collect(Collectors.toMap(a->a.getId(), a->a.getUsername()));//第一個參數爲map鍵值對中的key,第二個爲value
}
a爲形參名
將自身對象作爲value
public Map<Long, Account> getIdAccountMap(List<Account> accounts) {
return accounts.stream().collect(Collectors.toMap(Account::getId, account -> account));
}
account -> account是一個返回本身的lambda表達式,account爲形參,可任意替換,還可以使用Function接口中的一個默認方法代替,使整個方法更簡潔優雅:
public Map<Long, Account> getIdAccountMap(List<Account> accounts) {
return accounts.stream().collect(Collectors.toMap(Account::getId, Function.identity()));
}
key值重複問題
上述方法可能報錯(java.lang.IllegalStateException: Duplicate key),因爲name是有可能重複的。toMap有個重載方法,可以傳入一個合併的函數來解決key衝突問題:
public Map<String, Account> getNameAccountMap(List<Account> accounts) {
return accounts.stream().collect(Collectors.toMap(Account::getUsername, Function.identity(), (key1, key2) -> key2));
}
(key1,key2)->key2的意思爲,當key1,key2兩個鍵值對的key值重複時,保留第二個,->key1則保留第一個,同樣key1,key2只是形參名
完整代碼
public class Test{
public static void main(String[] args){
List<User> userList = new ArrayList();//存放user對象集合
User user1 = new User(1L, "張三", 24);
User user2 = new User(2L, "李四", 27);
User user3 = new User(3L, "王五", 21);
User user4 = new User(3L, "aaa",33);
userList.add(user1);
userList.add(user2);
userList.add(user3);
userList.add(user4);
//ID爲key,轉爲Map
Map<Long,User> userMap = userList.stream().collect(Collectors.toMap(User::getId, Function.identity(),(k1, k2)->k1));
for (Entry<Long, User> entry : userMap.entrySet()) {
System.out.println("key = " + entry.getKey() + ", value = " + entry.getValue().getName());
}
}
}
class User{
long id;
String name;
int age;
public User(long a, String b, int c) {
this.id = a;
this.name = b;
this.age = c;
}
public long getId() {
return id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
List中以對象某個屬性分組
public static void main(String[] args) {
List<User> userList = Lists.newArrayList();//存放user對象集合
User user1 = new User(1L, "張三", 24);
User user2 = new User(2L, "李四", 27);
User user3 = new User(3L, "王五", 21);
User user4 = new User(4L, "張三", 22);
User user5 = new User(5L, "李四", 20);
User user6 = new User(6L, "王五", 28);
userList.add(user1);
userList.add(user2);
userList.add(user3);
userList.add(user4);
userList.add(user5);
userList.add(user6);
//根據name來將userList分組
Map<String, List<User>> groupBy = userList.stream().collect(Collectors.groupingBy(User::getName));
System.out.println(groupBy);
}
過濾:從List中過濾出符合條件的元素
public static void main(String[] args) {
List<User> userList = Lists.newArrayList();//存放user對象集合
User user1 = new User(1L, "張三", 24);
User user2 = new User(2L, "李四", 27);
User user3 = new User(3L, "王五", 21);
User user4 = new User(4L, "張三", 22);
User user5 = new User(5L, "李四", 20);
User user6 = new User(6L, "王五", 28);
userList.add(user1);
userList.add(user2);
userList.add(user3);
userList.add(user4);
userList.add(user5);
userList.add(user6);
//取出名字爲張三的用戶
List<User> filterList = userList.stream().filter(user -> user.getName().equals("張三")).collect(Collectors.toList());
filterList.stream().forEach(user ->{
System.out.println(user.getName());
});
}
求和:將List中的數據按某個屬性求和
public static void main(String[] args) {
List<User> userList = Lists.newArrayList();//存放user對象集合
User user1 = new User(1L, "張三", 24);
User user2 = new User(2L, "李四", 27);
User user3 = new User(3L, "王五", 21);
User user4 = new User(4L, "張三", 22);
User user5 = new User(5L, "李四", 20);
User user6 = new User(6L, "王五", 28);
userList.add(user1);
userList.add(user2);
userList.add(user3);
userList.add(user4);
userList.add(user5);
userList.add(user6);
//取出名字爲張三的用戶
int totalAge = userList.stream().mapToInt(User::getAge).sum();
System.out.println("和:" + totalAge);
}
實戰:計算標準差
類中存在一個 public ArrayList<Double> classifier_cell = new ArrayList<Double>();
public double getStandard_Deviation() {
// 精度控制
DecimalFormat df = new DecimalFormat();
String style = "0.#####";// 定義要顯示的數字的格式
df.applyPattern(style);// 將格式應用於格式化器
// 計算標準差
int numOfCell = classifier_cell.size();
if (numOfCell == 1) {
return 0;
} else {
double sum = 0;//和
double nvariance = 0;//n倍方差
for (int j = 0; j < numOfCell; j++) {//求和
sum += classifier_cell.get(j);
}
double average = sum / numOfCell;//算平均值
for (int j = 0; j < numOfCell; j++) {//算n倍方差
nvariance += Math.pow((classifier_cell.get(j) - average), 2);
}
double standardDeviation = Math.sqrt(nvariance / numOfCell);//求標準差
return Double.parseDouble(df.format(standardDeviation));
}
}
改爲lambda
public double getStandard_Deviation() {
// 精度控制
DecimalFormat df = new DecimalFormat();
String style = "0.#####";// 定義要顯示的數字的格式
df.applyPattern(style);// 將格式應用於格式化器
// 計算標準差
int numOfCell = classifier_cell.size();
if (numOfCell == 1) {
return 0;
} else {
double average = classifier_cell.stream().mapToDouble(num->num).sum() / numOfCell;//平均數
double variance = classifier_cell.stream().mapToDouble(num->Math.pow(num-average,2)).sum() / numOfCell;//方差
double standardDeviation = Math.sqrt(variance);//標準差
return Double.parseDouble(df.format(standardDeviation));
}
}