gpt4 book ai didi

Java 循环遍历每个唯一值

转载 作者:行者123 更新时间:2023-12-02 03:52:46 25 4
gpt4 key购买 nike

我有一个像这样的 csv 文件:

"user1","track1","player1"
-------------------------
"user1","track2","player2"
-------------------------
"user1","track3","player3"
-------------------------
"user1","track4","player4"
-------------------------
"user2","track2","player3"
-------------------------
.
.
"userN","trackM","playerX"

我需要做的是将与每个用户相关的轨道和播放器分成两半,并将它们放在单独的文件中。例如,对于 user1,如果它有 4 行,我需要将其分为两部分(文件 A 中的前两行,文件 B 中的其余行),并对所有用户重复相同的操作。这是我到目前为止所写的:

public static void main(String[] args) throws java.lang.Exception { 

BufferedReader userlines = new BufferedReader(new FileReader("/Users/mona/Documents/Bolzano/Datasets/Lastfm_Matthias/lastfm_usertrackplayer.csv"));
String uLine = null;

while ((uLine = userlines.readLine()) != null) {

String[] userId = uLine.split(",");
ArrayList<String> list = new ArrayList<String>();
list.add(uLine);

for(int i=0; i<=list.size();i++){
// --> THIS FOR CONDITION IS MY PROBLEM,I need s.th like for(i=0; i<=(last unique userId (i.e., length of userId[i]) until it reaches the next unique userId)
//Divide the lines and put into two separate files

}
}
userlines.close();
}

抱歉,我知道这应该很简单,但我确实无法通过谷歌搜索我的问题找到任何相关/类似的问题:(有人可以帮我吗?

谢谢

最佳答案

您无法“先验”知道每个用户的行数。因此,您必须记住(例如在列表中)当前用户的所有行,直到读取下一个用户为止。然后在这两个文件中保存列表的内容。

清理列表,为下一个用户执行相同的操作。

编辑

public static void main(String[] args) throws java.lang.Exception { 

try(BufferedReader userlines = new BufferedReader(new FileReader("/Users/mona/Documents/Bolzano/Datasets/Lastfm_Matthias/lastfm_usertrackplayer.csv"));) {
String uLine = null;

ArrayList<String> list = new ArrayList<String>();
String currentUserId = null;
while ((uLine = userlines.readLine()) != null) {

String[] userData = uLine.split(",");
String userId = userData[0]; // <-- get User ID here
if (userId.equals(currentUserId)) {
// Do what ever you need while buffering same userId
} else {
// Save currentUserId in file
yourSaveMethod(list);
currentUserId = userId;
list.clear();
}
list.add(uLine);

}
}
}

关于Java 循环遍历每个唯一值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35743591/

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