英文:
How to split the integers in the array list?
问题
首先,抱歉英文表达不佳。在我的数组列表中,是否有可能将数字一分为二?我使用 .add 方法添加了每个数字。
public static void main(String[] args) {
ArrayList<Integer> num = new ArrayList<>();
num.add(24);
num.add(18);
num.add(12);
num.add(8);
num.add(20);
System.out.println(num);
}
输出结果:[24, 18, 12, 8, 20]
我想要将其一分为二,就像这样:
[12, 12, 9, 9, 6, 6, 4, 4, 10, 10]
英文:
first of all sorry for bad english.
Is it possible to split the numbers into half in my array list ?
I added each number using .add
public static void main(String[] args) {
ArrayList<Integer> num = new ArrayList<>();
num.add(24);
num.add(18);
num.add(12);
num.add(8);
num.add(20);
System.out.println(num);
}
Output: [24,18,12,8,20]
I want to split it into half
like this:
[12,12,9,9,6,6,4,4,10,10]
答案1
得分: 3
保持简单:
List<Integer> numSplit = new ArrayList<>();
for (Integer n : num) {
numSplit.add(n / 2);
numSplit.add(n / 2);
}
英文:
Keeping it simple:
List<Integer> numSplit = new ArrayList<>():
for (Integer n : num) {
numSplit.add(n / 2);
numSplit.add(n / 2);
}
答案2
得分: 3
List<Integer> num = Arrays.asList(24, 18, 12, 8, 20);
List<Integer> splitted = num.stream()
.flatMap(n -> Stream.of(n/2, n/2))
.collect(Collectors.toList());
英文:
You can also use a Java Stream with the flatMap method:
List<Integer> num = Arrays.asList(24, 18, 12, 8, 20);
List<Integer> splitted = num.stream()
.flatMap(n -> Stream.of(n/2, n/2))
.collect(Collectors.toList());
答案3
得分: 0
这是一种最简单的方法,没有考虑奇数。
public static void main(String[] args) {
ArrayList<Integer> num = new ArrayList<>();
num.add(24);
num.add(18);
num.add(12);
num.add(8);
num.add(20);
System.out.println(doJob(num));
}
private static List<Integer> doJob(List<Integer> lst){
List<Integer> retval = new ArrayList<>();
for(Integer a : lst){
for(int i = 0; i < 2; i++){
retval.add(a/2);
}
}
return retval;
}
英文:
This is a simplest approach without any consideration about odd numbers.
public static void main(String[] args) {
ArrayList<Integer> num = new ArrayList<>();
num.add(24);
num.add(18);
num.add(12);
num.add(8);
num.add(20);
System.out.println(doJob(num));
}
private static List<Integer> doJob(List<Integer> lst){
List<Integer> retval = new ArrayList<>();
for(Integer a : lst){
for(int i = 0; i < 2; i++){
retval.add(a/2);
}
}
return retval;
}
答案4
得分: 0
有另一种时髦的基于流的拆分方法,其中乘法和除法被位移操作 <<
和 >>
取代:
List<Integer> half2 = IntStream.range(0, num.size() << 1) // 从 0 到 2*n - 1 创建索引
.map(i -> num.get(i >> 1) >> 1) // 获取数组中“新”索引对应的相同元素,并将其除以 2
.boxed()
.collect(Collectors.toList());
英文:
There's another fancy stream-based way of splitting with multiplication and division replaced with shifts <<
and >>
:
List<Integer> half2 =IntStream.range(0, num.size() << 1) // create indexes from 0 to 2*n - 1
.map(i -> num.get(i>>1)>>1) // get the same element of array for "new" pair of indexes and divide it by 2
.boxed()
.collect(Collectors.toList());
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论