Is there a way of copying specific numbers from one array to another?
For example:
I have an array {1, 2, 3, 4, 5}
and I want to copy odd and even numbers to separate arrays. So, the result should be
{2, 4}, {1, 3, 5}
CodePudding user response:
Try this.
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5};
int[] even = IntStream.of(array).filter(i -> i % 2 == 0).toArray();
int[] odd = IntStream.of(array).filter(i -> i % 2 != 0).toArray();
System.out.println("even = " Arrays.toString(even));
System.out.println("odd = " Arrays.toString(odd));
}
output:
even = [2, 4]
odd = [1, 3, 5]
CodePudding user response:
int[] ls={1, 2, 3, 4, 5};
List<Integer> odd=new ArrayList<Integer>();
for (int l :ls) {
if(l%2==1) {
odd.add(l);
}
}
System.out.println(odd);
List<Integer> even=new ArrayList<Integer>();
for (int l :ls) {
if(l%2==0) {
even.add(l);
}
}
System.out.println(even);
CodePudding user response:
Try this
import java.util.*;
class Dragon {
public static void main(String[] args) {
int[] list = { 1, 2, 3, 4, 5 };
List<Integer> oddList = new ArrayList<Integer>();
List<Integer> evenList = new ArrayList<Integer>();
for (int l : list) {
if (l % 2 == 0)
evenList.add(l);
else
oddList.add(l);
}
System.out.println("Odd = " oddList);
System.out.println("Even = " evenList);
}
}
Output
Odd = [1, 3, 5]
Even = [2, 4]