@Slf4j
public class StreamUtils {
public static void main(String[] args) {
List<OptionAccount> accountList = getAccountList(100);
//根据币种ID将List的集合转换为Map
Map<Integer, OptionAccount> accoutMap = accountList.stream().collect(
Collectors.toMap(OptionAccount::getUserId, Function.identity()));
//log.info(accoutMap.toString());
//根据可用余额降序排序,然后在根据冻结额降序排序
List<OptionAccount> sortList = accountList.stream().sorted(Comparator.comparing(OptionAccount::getFree).reversed().
thenComparing(Comparator.comparing(OptionAccount::getFree).reversed()))
.collect(Collectors.toList());
//log.info(sortList.toString());
//根据币种ID进行分组
Map<Integer, List<OptionAccount>> groupMap = accountList.stream().collect(
Collectors.groupingBy(OptionAccount::getCoinId));
//log.info(JSON.toJSONString(groupMap));
//筛选币种ID大于等于且冻结月大于80的数据
List<OptionAccount> filterList = accountList.stream().filter(e->e.getCoinId()>=7&&e.getFrozen().compareTo(new BigDecimal("500"))>0).collect(Collectors.toList());
///log.info(JSON.toJSONString(filterList));
//获取集合中对象单独的某个字段(币种ID)作为新集合
List<Integer> rowList = accountList.stream().map(OptionAccount::getCoinId).collect(Collectors.toList());
//log.info(JSON.toJSONString( rowList ));
//去重
Set<OptionAccount> set = new HashSet<>(accountList);
log.info("原始集合大小"+accountList.size()+"=====去重后集合大小"+set.size());
}
public static List<OptionAccount> getAccountList(int n) {
List<OptionAccount> resList = new ArrayList<OptionAccount>();
OptionAccount optionAccount=null;
for (int i = 0; i < n; i++) {
optionAccount = new OptionAccount();
optionAccount.setUserId(randomInt(8));
optionAccount.setCoinId(randomInt(1));
optionAccount.setSymbol("USDT");
optionAccount.setFree(new BigDecimal(randomInt(8).toString()));
optionAccount.setFrozen(new BigDecimal(randomInt(3).toString()));
resList.add(optionAccount);
}
return resList;
}
public static Integer randomInt(int n) {
String str="";
for (int i = 0; i < n; i++) {
Random random = new Random();
str=str+random.nextInt(10);
}
return Integer.valueOf(str);
}
}
实体类
@Data
public class OptionAccount {
private Integer userId;
private Integer coinId;
private String symbol;
private BigDecimal free;
private BigDecimal frozen;
}