超详细利用Lambda处理List集合

遍历

 public static void main(String[] args) {
        List 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 getIdNameMap(List accounts) {
    return accounts.stream().collect(Collectors.toMap(Account::getId, Account::getUsername));//第一个参数为map键值对中的key,第二个为value
}

public Map getIdNameMap(List accounts) {
    return accounts.stream().collect(Collectors.toMap(a->a.getId(), a->a.getUsername()));//第一个参数为map键值对中的key,第二个为value
}

 a为形参名

将自身对象作为value

public Map getIdAccountMap(List accounts) {
    return accounts.stream().collect(Collectors.toMap(Account::getId, account -> account));
}

account -> account是一个返回本身的lambda表达式,account为形参,可任意替换,还可以使用Function接口中的一个默认方法代替,使整个方法更简洁优雅:

public Map getIdAccountMap(List accounts) {
    return accounts.stream().collect(Collectors.toMap(Account::getId, Function.identity()));
}

key值重复问题

上述方法可能报错(java.lang.IllegalStateException: Duplicate key),因为name是有可能重复的。toMap有个重载方法,可以传入一个合并的函数来解决key冲突问题:

public Map getNameAccountMap(List 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 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 userMap = userList.stream().collect(Collectors.toMap(User::getId, Function.identity(),(k1, k2)->k1));
            for (Entry 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 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> groupBy = userList.stream().collect(Collectors.groupingBy(User::getName));
        System.out.println(groupBy);

    }

过滤:从List中过滤出符合条件的元素

public static void main(String[] args) {
        List 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 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 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 classifier_cell = new ArrayList();

	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));
		}
	}

 

你可能感兴趣的:(Java)