尝试在列表中查找特定记录,然后创建一个包含11条记录的子列表,即5条记录高于所选记录,5条记录低于该记录。
可能的情景
以下是我目前的思考过程肯定会在此方法中添加更多检查,是否有更好的方法或任何其他建议
int s = myList.indexOf(tests);
if (s == 0) {
if (s + 2 < myList.size()) {
myList = myList.subList(s, s + 3);
} else {
myList = myList.subList(s, s);
}
} else if (s == 0 && s + 1 > myList.size()) {
myList = myList.subList(s, s);
} else if (s - 1 > 0 && s + 1 < myList.size()) {
myList = myList.subList(s - 1, s + 2);
} else if (s + 1 >= myList.size()) {
myList = myList.subList(s - 1, s + 1);
} else if (s == myList.size() - 1) {
if (s - 2 > 0) {
myList = myList.subList(s - 2, s + 1);
} else {
myList = myList.subList(s, s + 1);
}
}
答案 0 :(得分:2)
试试这个,
List<String> records = Arrays.asList("one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen");
final List<String> subRecords = IntStream.range(0, records.size()).filter(i -> records.get(i).equals("eight"))
.mapToObj(i -> records.subList(Math.max(i - 5, 0), Math.min(i + 6, records.size())))
.flatMap(List::stream).collect(Collectors.toList());
注意我使用List
String
作为源记录。根据你的情况改变它。
或者可以这样做,
final int midIdx = records.indexOf("eight");
final int lowerBound = Math.max(midIdx - 5, 0);
final int upperBound = Math.min(midIdx + 5, records.size());
final List<String> subRecords = IntStream.range(0, records.size()).limit(upperBound + 1).skip(lowerBound)
.mapToObj(records::get).collect(Collectors.toList());
<强>更新强>
我通过以下评论建议了更改,因为它简化了代码。