首页 > 解决方案 > 如何在另一个集合中搜索一个集合的项目

问题描述

嗨,我有两个集合,它们是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>. 换句话说,我想从下面获取我拥有的' Assets 的价格并创建如下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],
]

我试图简化我的问题。所以我不确定是否应该使用ListSet为了保持性能和使用流

标签: javaset

解决方案


用于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()));
}

推荐阅读