Home > Back-end >  Select positives from a list with Generics
Select positives from a list with Generics

Time:12-30

I am pretty new here, so excuse me if you do not understand my question.(Be nice :D) So basically I have to make a method which select positives "numbers" from a list using Generics.

The base of the method should look like this :

public static <T> List<T> selectPositives(List<? extends Number> list) {

        T positiveNumber = null;
        for (int i = 0; i < list.size(); i  ) {
            if (list.get(i) > 0) {
                return (List<T>) positiveNumber;
            }
        }
        return (List<T>) positiveNumber;
    }

Well obviously this is not working, so I would greatly appreciate any help. Thanks, Alma

CodePudding user response:

I modified your code so that it would return a list of positive numbers.

    //public static <T> List<T> selectPositives(List<? extends Number> list) {
    public static <T extends Number> List<T> selectPositives(List<T> list) {
        //T positiveNumber = null;
        List<T> positiveNumbers = new ArrayList<>();
        for (int i = 0; i < list.size(); i  ) {
            if (list.get(i).doubleValue() > 0) {
                //return (List<T>) positiveNumber;
                positiveNumbers.add(list.get(i));
            }
        }
        return positiveNumbers;
    }

    public static void main(String[] args) {
        
        List<Number> list = List.of(-1,-2,1.5, 3,-4,-5, 6);
        System.out.println(selectPositives(list));
    }

Output:

[1.5, 3, 6]

CodePudding user response:

Using Stream API, the list of positives may be filtered out of the input:

public static <T extends Number> List<T> selectPositives(List<T> list) {
    return list.stream()
        .filter(x -> x.doubleValue() > 0.0)
        .collect(Collectors.toList());
} 

Also, List::removeIf with inverted condition may be applied to the given input/mutable copy of the input:

public static <T extends Number> List<T> selectPositives(List<T> list) {

    List<T> result = new ArrayList<>(list);
    
    result.removeIf(x -> x.doubleValue() <= 0);
    
    return result;
}

CodePudding user response:

public static List<? extends Number> selectPositives(List<? extends Number> list) {
    final List<Number> result = new ArrayList<>();

    for (final Number inputNumber : list) {
        if (BigDecimal.valueOf(inputNumber.doubleValue())
                .compareTo(BigDecimal.ZERO) >= 0) {
            result.add(inputNumber);
        }
    }

    return result;
}

CodePudding user response:

check for absolute value of the number, then compare it to the number without abs. if they match, then it's positive, and if not its negative.

add the elements that match to another list to have all the positive numbers in the list

  • Related