有会用java8的 stream()写法吗. 实现下面这样的.
String[] arrs = {"A", "B", "C", "D", "E", "F"};
List<String> as = new LinkedList<>();
List<String> bs = new LinkedList<>();
int i = 0;
for (String arr : arrs) {
i++;
if (i % 2 == 0) {
as.add(arr);
} else {
bs.add(arr);
}
}
java的不会,C#的给你写一个,思路是将原始数据编号,然后根据编号的奇数偶数分组
C#写法
string[] arrs = {"A", "B", "C", "D", "E", "F"};
var query = arrs.Select((x, i) => new {x , i}).GroupBy(x => x.i % 2).Select(x => x.Select(y => y.x).ToList()).ToArray();
var as = query[0];
var as = query[1];
String[] arrs = {"A", "B", "C", "D", "E", "F"};
List<String> as = new LinkedList<>();
List<String> bs = new LinkedList<>();
final int[] i = {0};
Arrays.stream(arrs).forEach(a -> {
i[0]++;
if (i[0] % 2 == 0) {
as.add(a);
} else {
bs.add(a);
}
});
这种不是随便百度就能知道的么?
String[] arrs = {"A", "B", "C", "D", "E", "F"};
List<String> as = new LinkedList<>();
List<String> bs = new LinkedList<>();
final int[] i = {0};
Arrays.asList(arrs).stream().forEach(a -> {
i[0]++;
if (i[0] % 2 == 0) {
as.add(a);
} else {
bs.add(a);
}
});
我这儿有一种方法
List<String> list = Arrays.asList("A", "B", "C", "D", "E", "F");
List<String> as = list.stream().filter(s->list.indexOf(s) % 2 == 1).collect(Collectors.toList());
List<String> bs = list.stream().filter(s->list.indexOf(s) % 2 == 0).collect(Collectors.toList());