import com.alibaba.fastjson.JSON;
import org.springframework.beans.BeanUtils;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @author
* @date 2019-12-30 17:47
* @description
*/
public class TestMain {
public static void main(String[] args) {
List<User> list = new ArrayList<>();
User user1 = new User();
user1.setUserId("11111");
user1.setUserName("张三");
user1.setAmount(BigDecimal.valueOf(1500));
User user2 = new User();
user2.setUserId("11111");
user2.setUserName("张三");
user2.setAmount(BigDecimal.valueOf(200));
User user3 = new User();
user3.setUserId("22222");
user3.setUserName("李四");
user3.setAmount(BigDecimal.valueOf(2000));
list.add(user1);
list.add(user2);
list.add(user3);
List<User> data = merged(list);
System.out.println(JSON.toJSONString(data));
}
/**
* 根据用户ID、用户名对集合中的数据去重,并且合并金额的值
* @param list
* @return
*/
private static List<User> merged(List<User> list) {
List<User> data = new ArrayList<>();
// Collectors.groupingBy根据指定字符串分组排序,由于需要根据多个属性,先把多个属性拼接成一个字符串
Map<String, List<User>> collect = list.stream().collect(Collectors.groupingBy(e -> fetchGroupKey(e)));
for (Map.Entry<String, List<User>> entry : collect.entrySet()) {
User user = new User();
// 使用BeanUtils进行重新赋值到新的对象当中,因为合并,所以只需要保留分组后的一个对象的值
BeanUtils.copyProperties(entry.getValue().get(0), user);
// 由于需要返回一个新的值所以使用map而不是使用forEach,对集合当中的对象某一个属性的值进行相加
BigDecimal total = entry.getValue().stream().map(User::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
user.setAmount(total);
data.add(user);
}
return data;
}
/**
* 根据多个属性拼接成一个字符串
* @param user
* @return
*/
private static String fetchGroupKey(User user) {
return user.getUserId() + user.getUserName();
}
}
运行输出
[{"amount":2000,"userId":"22222","userName":"李四"},{"amount":1700,"userId":"11111","userName":"张三"}]
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @author
* @date 2019-12-30 17:47
* @description
*/
public class SortUtils {
/**
* 对map的key进行排序
* @param map
* @return
*/
public static Map<String, String> sortMapKey(Map<String,String> map) {
Map<String, String> result = map.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(oleValue, newValue) -> oleValue, LinkedHashMap::new));
return result;
}
/**
* 对map的value进行排序
* @param map
* @return
*/
public static Map<String,String> sortMapValue(Map<String,String> map){
Map<String, String> result = map.entrySet().stream()
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(oldValue, newValue) -> oldValue, LinkedHashMap::new));
return result;
}
}
来源:CSDN
作者:码农的诞生
链接:https://blog.csdn.net/m0_37845840/article/details/103770621