我有一个csv文件是' |'分隔,并有多行。文件中的某些条目有重复项,我需要将这些条目合并为一行。然后,这些条目将用于创建地图对象。我是java的新手,需要有关如何执行此操作的帮助。我创建了一个地图对象,但不知道如何处理重复项。谁能建议如何在java中做到这一点?
我的清单:
HR |325|50051710|CN=ADGroup1
HR |325|50051710|CN=ADGroup2
BA |375|50110084|CN=ADGroup1
SYS ADMIN |877|50145471|CN=ADGroup2
输出必须像这样被读作地图对象:
HR |325|50051710|CN=ADGroup1,CN=ADGroup2
BA |375|50110084|CN=ADGroup1
...
我的代码:
Map attrList = new HashMap();
String[] record = line.split("\\|");
try{
br1 = new BufferedReader(new FileReader(inputFile));
String line = "";
while ((line = br1.readLine()) != null) {
if (record[1] != null ) {
Map map = new HashMap();
String costcentre = record[1].trim();
map.put("Costcentre", costcentre);
String jobcode = record[2].trim();
map.put("Jobcode", jobcode);
String adgroup = record[3].trim();
map.put("ADGroup", adgroup);
attrList.put(costcentre + jobcode, map);
答案 0 :(得分:0)
我制作了这段代码,我相信它可以解决你的问题(让我知道它是否确实如此):
{
String tempString, group;
Map<String, String> myMap = new HashMap<String, String>();
List<String> myList;
myList = createListFromFile("myFile.txt");
for(String string : myList){
tempString = string.substring(0, string.lastIndexOf('|'));
group = string.substring(string.lastIndexOf('|'), string.length());
if(myMap.containsKey(tempString)){
//substring is used here to remove '|' character
myMap.put(tempString, myMap.get(tempString) +","+group.substring(1, group.length()));
}else{
myMap.put(tempString, tempString + group);
}
}
//For testing
for (Map.Entry<String,String> entry : myMap.entrySet()) {
System.out.println("key = "+entry.getKey());
System.out.println("value = "+entry.getValue());
}
}
public static List<String> createListFromFile(String path){
//you might need to change the Charset
Charset charsetUTF8 = Charset.forName("UTF-8");
List<String> lines = null;
try {
lines = Files.readAllLines(Paths.get(path), charsetUTF8);
} catch (IOException e) {
e.printStackTrace();
}
return lines;
}