Reputation: 57
public static List<Integer> removeOddNumbers(ArrayList<Integer> list) {
if (list.isEmpty()) { throw new Error(); }
List<Integer> toRemove = new ArrayList<>();
for (int i : list) {
if (i % 2 != 0) { toRemove.add(i); }
}
list.removeAll(toRemove);
return list;
}
I'm trying to remove all odd elements from an ArrayList and then returning that ArrayList.
I'm getting an error pointing to List Integer in this first line
Test:
ArrayList<Integer> arrayList = new ArrayList<Integer>();
Collections.addAll(arrayList, 3, 5, 6, 24, 7, 9, 1, 8, 28, 11);
ArrayList<Integer> result = removeOddNumbers(arrayList);
System.out.println(result);
Result:
[6, 24, 8, 28]
Upvotes: 3
Views: 8074
Reputation: 60016
If you are using Java 8, you can just use Collection::removeIf :
list.removeIf(i -> i % 2 != 0);
The full method should look like this :
public static List<Integer> removeOddNumbers(List<Integer> list) {
list.removeIf(i -> i % 2 != 0);
return list;
}
Example
List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 6, 5, 4));
list.removeIf(i -> i % 2 != 0);
System.out.println(removeOddNumbers(list));
Outputs
[2, 6, 4]
Upvotes: 2
Reputation: 1403
lambda way :
public static List<Integer> filter(List<Integer> numberList) {
return numberList.stream()
.filter(number -> number % 2 != 0)
.collect(Collectors.toList());
}
You should call this method with this :
List<Integer> list = Arrays.asList(3, 5, 6, 24, 7, 9, 1, 8, 28, 11);
List<Integer> result = removeOddNumbers(numbers);
System.out.println(result);
The problem is that the returning type of the method is List<Integer>
but your code expect an ArrayList
the solution is to simply use the generic class List
or if you want use your code it should be like this :
ArrayList<Integer> arrayList = new ArrayList<Integer>();
Collections.addAll(arrayList, 3, 5, 6, 24, 7, 9, 1, 8, 28, 11);
List<Integer> result = removeOddNumbers(arrayList);
System.out.println(result);
N.B The method posted by @YCF_L edit the list that you pass by the parameter, my method instead create a new list leaving the original list untouched
Upvotes: 1
Reputation: 73
You should go for Iterator to remove items from List. That would save the usage of a temporary list where you store odd elements.
public static List<Integer> removeOddNumbers(List<Integer> arrayList) {
Iterator<Integer> itr = arrayList .iterator();
while (itr.hasNext())
{
int x = (Integer)itr.next();
if (x % 2 != 0) {
itr.remove();
}
}
return arrayList;
}
OR
You can go for a lot easier code with Java8.
Upvotes: 4
Reputation: 9
// you can use Iterator.remove()
List arr = new ArrayList();
arr .add(10);
arr .add(20);
arr .add(30);
arr .add(1);
arr .add(2);
// Remove odd elements
// Iterator.remove()
Iterator itr = arr .iterator();
while (itr.hasNext())
{
int x = (Integer)itr.next();
if (x % 2 != 0)
itr.remove();
}
System.out.println("Modified ArrayList : " + arr);
Upvotes: 0