gpt4 book ai didi

Java - 将 StringTokenizer 保存到数组中以便在其他方法中进一步处理

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

我一直在编写 Perl 和 Python 代码,这次我得到了一个用 Java 编写代码的任务。所以我不太熟悉在 Java 中处理数据。

我的任务涉及拥有一个输入文件,我需要在其中检查依赖项,然后输出具有传递依赖项的那些。下面更清晰的想法:

输入文件:

A: B C
B: C E
C: G
D: A

输出文件:
A: B C E G
B: C E G
C: G
D: A B C E G

到目前为止,这是我所得到的(将第一个和第二个标记分开):
import java.util.StringTokenizer;
import java.io.*;

public class TestDependency {

public static void main(String[] args) {

try{

FileInputStream fstream = new FileInputStream("input-file");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;

while ((strLine = br.readLine()) != null) {
StringTokenizer items = new StringTokenizer(strLine, ":");

System.out.println("I: " + items.nextToken().trim());

StringTokenizer depn = new StringTokenizer(items.nextToken().trim(), " ");

while(depn.hasMoreTokens()) {
System.out.println( "D: " + depn.nextToken().trim() );
}
}

} catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}

任何帮助表示赞赏。我可以想象 Perl 或 Python 可以轻松处理这个问题。只需要在Java中实现它。

最佳答案

这在内存方面不是很有效,需要良好的输入,但应该运行良好。

public class NodeParser {

// Map holding references to nodes
private Map<String, List<String>> nodeReferenceMap;

/**
* Parse file and create key/node array pairs
* @param inputFile
* @return
* @throws IOException
*/
public Map<String, List<String>> parseNodes(String inputFile) throws IOException {

// Reset list if reusing same object
nodeReferenceMap = new HashMap<String, List<String>>();

// Read file
FileInputStream fstream = new FileInputStream(inputFile);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;

// Parse nodes into reference mapping
while((strLine = br.readLine()) != null) {
// Split key from nodes
String[] tokens = strLine.split(":");
String key = tokens[0].trim();
String[] nodes = tokens[1].trim().split(" ");
// Set nodes as an array list for key
nodeReferenceMap.put(key, Arrays.asList(nodes));
}

// Recursively build node mapping
Map<String, Set<String>> parsedNodeMap = new HashMap<String, Set<String>>();
for(Map.Entry<String, List<String>> entry : nodeReferenceMap.entrySet()) {
String key = entry.getKey();
List<String> nodes = entry.getValue();
// Create initial node set
Set<String> outSet = new HashSet<String>();
parsedNodeMap.put(key, outSet);
// Start recursive call
addNode(outSet, nodes);
}

// Sort keys
List<String> sortedKeys = new ArrayList<String>(parsedNodeMap.keySet());
Collections.sort(sortedKeys);

// Sort nodes
Map<String, List<String>> sortedParsedNodeMap = new LinkedHashMap<String, List<String>>();
for(String key : sortedKeys) {
List<String> sortedNodes = new ArrayList<String>(parsedNodeMap.get(key));
Collections.sort(sortedNodes);
sortedParsedNodeMap.put(key, sortedNodes);
}

// Return sorted key/node mapping
return sortedParsedNodeMap;
}

/**
* Recursively add nodes by referencing the previously generated list mapping
* @param outSet
* @param nodes
*/
private void addNode(Set<String> outSet, List<String> nodes) {
// Add each node to the set mapping
for(String node : nodes) {
outSet.add(node);
// Get referenced nodes
List<String> nodeList = nodeReferenceMap.get(node);
if(nodeList != null) {
// Create array list from abstract list for remove support
List<String> referencedNodes = new ArrayList<String>(nodeList);
// Remove already searched nodes to prevent infinite recursion
referencedNodes.removeAll(outSet);
// Recursively search more node paths
if(!referencedNodes.isEmpty()) {
addNode(outSet, referencedNodes);
}
}
}
}
}

然后,您可以像这样从程序中调用它:
    public static void main(String[] args) {
try {
NodeParser nodeParser = new NodeParser();
Map<String, List<String>> nodeSet = nodeParser.parseNodes("./res/input.txt");
for(Map.Entry<String, List<String>> entry : nodeSet.entrySet()) {
String key = entry.getKey();
List<String> nodes = entry.getValue();
System.out.println(key + ": " + nodes);
}
} catch (IOException e){
System.err.println("Error: " + e.getMessage());
}
}

此外,输出没有排序,但这应该是微不足道的。

关于Java - 将 StringTokenizer 保存到数组中以便在其他方法中进一步处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7621478/

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