运用场景(交易所深度增量推送)
- [[411.8,6],[411.75,11],[411.6,22],[411.5,9],[411.3,16]]
- [[411.8,5],[411.7,11],[411.5,22],[411.5,9],[411.3,1]]
import java.util.ArrayList;
import java.util.List;
public class two {
public static void main(String[] args) {
/**
* 两个集合是有序的,从大到小的
*
* 1).集合now有集合old没有的 ,添加
*
* 2).集合now有集合old有的的 ,舍弃
*
* 3).集合now没有但是集合old有的 ,数量标志位0
*
* 4).集合now有集合old也有的 但是数量不一致的 变更
*/
//String[] 长度为2 第一个数据为价格,第二个数据为数量
List<String[]> now = new ArrayList<String[]>();
List<String[]> old = new ArrayList<String[]>();
StringBuilder data = new StringBuilder();// 用于拼接最后的数据
int oldSize = old.size();
int nowSize = now.size();
int index = 0; // now 集合索引
int last_index = 0;// old 集合索引
for (int i = 0, size = oldSize + nowSize; i < size; i++) {
if (last_index >= oldSize && index >= nowSize) {//如果两个数据的每个元素都一致
break;
}
double price = -1d;
String amount = "";
if (index < nowSize) {
price = Double.parseDouble(now.get(index)[0]);
amount = now.get(index)[1];
}
double lastPrice = -1d;
String lastAmount = "";
if (last_index < oldSize) {
lastPrice = Double.parseDouble(old.get(last_index)[0]);
lastAmount = old.get(last_index)[1];
}
if (price == lastPrice) {
if (!amount.equals(lastAmount)) {
data.append("[" + price + "," + amount + "],");
}
last_index++;
index++;
} else if (price > lastPrice) {
data.append("[" + price + "," + amount + "],");
index++;
} else if (price < lastPrice) {
data.append("[" + price + "," + 0 + "],");
last_index++;
}
}
}
}