gpt4 book ai didi

java - 从边缘删除值

转载 作者:行者123 更新时间:2023-12-02 06:30:04 25 4
gpt4 key购买 nike

我有以下格式的数据

String [] data = new String[]{"-166444026   0   file    20130801",
"-166444026 0 file 20130802",
"-166444027 0 file 20130802"};

这些是制表符分隔的字符串。现在..所以我们有键、值、类型、日期。

我想要的是在列表中保留最新的唯一键。那么例如...此操作的输出应该是...

["-166444026    0   file    20130802",
"-166444027 0 file 20130802"];

因为 -166444026 出现了两次,但我删除的那个日期为 20130801,而这个日期更晚?

我写了代码..但这只是返回所有内容。(我以为它应该删除..但事实并非如此..)??

有什么线索吗?

package org.random_scripts;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.json.simple.JSONObject;

public class Regex {
private static boolean alreadyExists(Map<String, Long> dict, String key) {
if(dict.containsKey(key))
return true;
return false;
}
private static void removeEdge(ArrayList<JSONObject>edgeList, String key) {

for(JSONObject edge:edgeList) {
if (edge.get("destination").equals(key))
edge.remove(key);
}
}

public static void main(String[] args) {

String [] data = new String[]{"-166444026 0 file 20130801",
"-166444026 0 file 20130802",
"-166444026 0 file 20130802"};

try {
String key = "185479485";
JSONObject jsn = new JSONObject();
jsn.put("source", key.toString());

ArrayList<JSONObject> edges = new ArrayList<JSONObject>();
Map<String, Long> tracker = new HashMap<String, Long>();
for (int i=0; i < data.length; i++) {
String value = data[i];
//edgeString+= value.toString()+",";
String[] typeChunks = value.toString().split("\t");

String destination = typeChunks[0];
Double reputation = Double.parseDouble(String.valueOf(typeChunks[1]));
System.out.println(tracker.values().toString());
JSONObject edgeJson = new JSONObject();
Long date = Long.valueOf(typeChunks[3]);
if(alreadyExists(tracker,destination)) {
Long prev_date = tracker.get(destination);
System.out.println(true);
if (date > prev_date) {
//remove edge
removeEdge(edges,destination);
System.out.println("edges are" + edges.toString());

}
}
else {
tracker.put(destination, date);

}


edgeJson.put("destination", destination);
edgeJson.put("reputation", reputation);
edgeJson.put("type", typeChunks[2]);
edges.add(edgeJson);

}
jsn.put("edgelist", edges);
System.out.println(jsn.toJSONString());
//context.write(NullWritable.get(), new Text(jsn.toJSONString()));
//edgeString = edgeString.substring(0,edgeString.length()-1);
//edgeString+="]";
}
catch (Exception e) {
System.out.println("Exceptiom");
//context.write(NullWritable.get(),new Text(s) );
}




}

}

最佳答案

使用 HashMap ,然后将每一行分配给 HashMap 中的一个键。

HashMap 将仅保留最新分配的值,因此您可以根据其日期决定是否要重新分配它。

如果需要保留行的原始顺序,可以使用 LinkedHashMap它保留插入顺序。

希望有帮助。

关于java - 从边缘删除值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20150954/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com