3 回答
![?](http://img1.sycdn.imooc.com/545847f50001126402200220-100-100.jpg)
TA贡献1818条经验 获得超8个赞
使用模运算符和单个循环的解决方案。没有 IndexOutOfBounds 的风险。
for (int i = 0; i < list.length; i++) {
if (i % 6 > 2) {
System.out.println(list[i]);
}
}
i % 6 < 3如果您想要数组中每 6 个元素中的前 3 个,则可以将条件翻转为。
编辑:以下内容接受您的输入并将其放入List<String[]>每个元素包含 3 行的位置。
import java.nio.file.*;
import java.util.stream.Stream;
import java.util.*;
import java.nio.charset.Charset;
public class Partition2 {
public static void main(String[] args) {
String[] input = ...
try (Stream<String> stream = Arrays.stream(input)) {
// https://stackoverflow.com/a/34759493/3717691
String[] array = stream.map(line -> line.trim()).filter(line -> !line.isEmpty()).toArray(String[]::new);
List<String[]> results = new ArrayList<String[]>();
String[] tmp = new String[3];
for (int i = 0; i < array.length; i++) {
tmp[i % 3] = array[i];
if (i % 3 == 2) {
results.add(tmp);
tmp = new String[3];
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
![?](http://img1.sycdn.imooc.com/54584f8f00019fc002200220-100-100.jpg)
TA贡献1906条经验 获得超3个赞
for(int i=3;i<s1.length;i+=6){
for(int j=0;j<3;j++){
s1[i+j]; // here is your element
}
}
IndexOutOfBoundsException如果 arrag 大小不能被 6 整除,只需调整循环条件即可
![?](http://img1.sycdn.imooc.com/545850200001359c02200220-100-100.jpg)
TA贡献1943条经验 获得超7个赞
您可以使用 Java 8 流。如果s有类型E:
List<E> collect =
IntStream.range(0, s.length) // 0...n-1
.filter(i -> i/3%2 == 0) // g = i/3 is the number of the group and we take one group out of to (g % 2 == 0)
.mapToObj(i -> s[i]) // take s[i]
.collect(Collectors.toList());
添加回答
举报