【发布时间】:2016-07-06 11:07:33
【问题描述】:
我需要找出属于另一个元素的最大元素。举个例子最清楚。
我的List<String> lines 包含以下数据:
1, 1, A, Aaa ...
1, 2, A, Aaa ...
1, 4, A, Aaa ...
2, 5, B, Bbb ...
2, 3, B, Bbb ...
3, 6, C, Ccc ...
4, 7, D, Ddd ...
5, 8, E, Eee ...
1, 9, A, Aaa ...
4, 10, D, Ddd ...
需要明确的是,两对数字永远不会相同,所以你永远不会得到:
1, 9, A, Aaa ...
1, 9, B, Bbb ...
我的目标是提取属于第一行的第二行最大值的行。确切地说是这些行:
1, 9, A, Aaa ...
2, 5, B, Bbb ...
3, 6, C, Ccc ...
4, 10, D, Ddd ...
5, 8, E, Eee ...
为了证明这不是作业,我使用多个for-loop 来找到最大值并存储到变量中。但是我不知道它是否有效,因为测试了大量数据 (200 000+)。
// List "lines" is declared above
List<List<String>> data = new ArrayList<>();
List<List<String>> maxValues = new ArrayList<>();
// clear and separate to clear comparable parts
for (String s: lines) {
String parts[] = s.trim().replace("\"", "").split(";");
List newList = Arrays.asList(parts);
data.add(newList);
}
// naïve algorithm to find the maximum dependent to the another one
// not sure if working
for (List l: data) {
int id = Integer.parseInt(l.get(0).toString());
int max = 0;
List<String> tempMaxValues = new ArrayList<>();
for (int i=0; i<data.size(); i++) {
if (Integer.parseInt(l.get(0).toString()) == id) {
int temp = Integer.parseInt(l.get(1).toString());
if (temp > max) {
max = temp;
tempMaxValues = l;
}
}
}
maxValues.add(tempMaxValues);
}
此外,我需要做更多的计算。只有Stream 或更简单的方法才能达到我想要的结果?即使在我的代码中,我也会迷失方向。
【问题讨论】:
-
寻求家庭作业的帮助并没有什么不好,坏的是没有努力产生自己的解决方案:)
-
恐怕我不明白
with the maximum of second row that belongs to the first row的意思。你能扩展一下吗? -
@Sasha Salauyou:这确实不是功课。如果是这样,我可以坦率地承认这一点。 :) 我这样做是我在之前的工作中遇到的挑战,但在这种情况下我们使用了更好的 SQL。
-
@PaulBoddington:这就是为什么会有样本输入和期望的结果。
-
@PaulBoddington:这永远不会发生。两个值永远不会与另一个值相同。我编辑了,谢谢你的提示:)
标签: java list optimization arraylist java-stream