Search code examples
javalistarraylistcharacter

Checking the type of the Array elements


I've managed to add the user input into the ArrayList.

Now I want to split this list. So that letters are with letters, numbers are with numbers.

I.e, I want to obtain two separate lists (or arrays): digits and letters. Is there a way to do this?

I'm new to java, so for now I don't see where to go. I think that I need to check each of the elements of the array against the type int and char (String ?), but I don't understand how to do it.

public class BaseClass {
    
    public static void main(String[] args) {
    
        Scanner takeData = new Scanner(System.in);
    
        String str = takeData.nextLine();
        ArrayList<Character> chars = new ArrayList<Character>();
        for (char c : str.toCharArray()) {
            chars.add(c);
        }
    
        System.out.println(chars);
    }
}

Solution

  • Now I want to sort it so that letters are with letters, numbers are with numbers

    So you want to sort the given list so that digits will be separated from letters.

    You can do it by defining a custom Comparator (which is a special object used to compare two objects and define the order of elements of a collection, stream, etc.).

    Down below is a comparator that firstly determines whether the given character is a digit and then compares characters according to their natural ordering (have a look at this tutorial for more information on Java-8 comparators).

    List<Character> chars = new ArrayList<>(List.of('1', 'a', '2', 'b', 'c', '3'));
    
    Comparator<Character> lettersFirst = 
        Comparator.comparing((Character ch) -> Character.isDigit(ch))
                  .thenComparing(Comparator.naturalOrder());
    
    chars.sort(lettersFirst);
    System.out.println(chars);
    

    Output

    [a, b, c, 1, 2, 3]
    

    I want to obtain two separate lists (or arrays): digits and letters.

    If you just need to separate digit from letters without sorting them and omit other symbols, you can use static methods of the Character class isLetter() and isDigit().

    String str = "lemon 123 abc";
    List<Character> digits = new ArrayList<>();
    List<Character> letters = new ArrayList<>();
    for (int i = 0; i < str.length(); i++) {
        char next = str.charAt(i);
        if (Character.isDigit(next)) {
            digits.add(next);
        } else if (Character.isLetter(next)) {
            letters.add(next);
        }
    }
        
    System.out.println("Letters: " + letters);
    System.out.println("Digits: " + digits);
    

    Output

    Letters: [l, e, m, o, n, a, b, c]
    Digits: [1, 2, 3]