jessss jessss - 6 months ago 23
Java Question

Positive and negative numbers with ArrayList

How do I seprate positive and negative numbers? I have this code:

import java.util.ArrayList;
import java.swing.JOptionPane;

public class Test {
public static void main(String[] args) {
ArrayList al = new ArrayList();

int num=Integer.parseInt(JOptionPane.showInputDialog("How many numbers?"));
for (int i=0 ; i < num ; i++) {
al.add(Integer.parseInt(JOptionPane.showInputDialog("What numbers?")));
}
}
}


Let's say I want to add 5 numbers.
-2, -7, 8, 4, -1


I need the output to be
Positive = 8, 4
and
Negative = -2, -7, -1

Answer

If you use Java 8, you can use stream to separate them easily:

List<Integer> positive = new ArrayList<>();
List<Integer> negative = new ArrayList<>();
al.stream().forEach(i -> (i < 0 ? negative : positive).add(i));
System.out.println(positive);
System.out.println(negative);

You have two lists one containing positive, the other containing negative.