java8中Stream常用特性代码实战

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值