java - 如何在另一个集合中搜索一个集合的项目
问题描述
嗨,我有两个集合,它们是Set<Price>
andSet<Balance>
和一个类
public class Price{
private String symbol;
private String price;
}
public class Balance{
private String asset;
private String amount;
}
public class Response{
private String symbol;
private double amount;
private double value
}
Set<Price> prices = new HashSet<Price>();
Set<Balance> balances = new HashSet<Balance>();
我将这些记录添加到集合中:
[
Price[symbol=NEO,price=0.031],
Price[symbol=BTC,price=0.010],
Price[symbol=ETH,price=0.075],
Price[symbol=ABC,price=0.045],
Price[symbol=XYZ,price=0.019],
//..Thousands records
]
[
Asset[asset=ETH,amount=0.23],
Asset[asset=XYZ,amount=0.23],
//.. Very small relative to prices
]
我想创建Set<Response>
关于Set<Asset>
. 换句话说,我想从下面获取我拥有的' Asset
s 的价格并创建如下Set<Asset>
Set<Price>
Set<Response>
[
Response[symbol=ETH, amount=0.23, value=0.23*0.075],
Response[symbol=XYZ, amount=1.68, value=1.68*0.019],
]
我试图简化我的问题。所以我不确定是否应该使用List
或Set
为了保持性能和使用流
解决方案
用于Map<String,Double> price = new HashMap<>()
存储每个品种的价格。然后构建响应很容易 - 无论是使用循环还是使用流。
流:
Set<Balance> balances = new HashSet<>();
...
Set<Response> responses = balances.stream()
.map(b -> new Response(b.getAsset(),
b.getAmmount(),
b.getValue() * prices.get(b.getAsset()))
.collect(Collectors.toSet());
环形:
Set<Balance> balances = new HashSet<>();
Set<Response> responses = new HashSet<>();
for(Balance b : balances) {
responses.add(new new Response(b.getAsset(),
b.getAmmount(),
b.getValue() * prices.get(b.getAsset()));
}
推荐阅读
- python - discord.py 图像“需要一个类似字节的对象,而不是 'int'”
- python - 我需要编写一个从标准输入读取整数的程序,并且对于每个整数读取,将 pi 打印到小数位数
- python - 为什么应用于 TSP 的这种模拟退火算法不收敛?
- php - 图片上传 Laravel 和 Windows Server 2019 失败
- python - conda build 错误:找不到 pytest-runner 的匹配分布
- java - 重定向到另一个页面时如何保存数据
- r - 仅在下载时禁止数据表中的行名
- python - Numpy uint16 加法无溢出异常
- python - 可以monkeypatch numpy 数组切片行为吗?
- css - 为什么我的汉堡菜单上的转换不起作用?