我需要找出属于另一个元素的最大元素。给你一个例子是最清楚的。基于另一个列表中元素的最大值
我有一个包含以下数据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
或更简单的方法才有可能达到我想要的结果?即使在我的代码中,我也迷迷糊糊。
有没有不好的要求帮助做功课,不好的是没有努力来制定自己的解决方案:) –
恐怕我不明白“属于第一行的第二行的最大值”的含义。你可以扩展这个吗? –
@Sasha Salauyou:这确实不是一项家庭作业。如果是这样,我可以自由承认这一点。 :)我这样做是我在以前的工作中遇到的挑战,但我们在这种情况下使用了更好的SQL。 –