sort Integer values in decending order with null values in java using streams
- User
sort Integer values in decending order with null values in java using streams
Assistant
import java.util.Arrays; import java.util.Comparator; import java.util.stream.Collectors;
public class SortInteger { public static void main(String[] args) { Integer[] numbers = {7, null, 5, 3, null, 9, 1}; Integer[] sortedNumbers = sortIntegersDescending(numbers); System.out.println(Arrays.toString(sortedNumbers)); }
codepublic static Integer[] sortIntegersDescending(Integer[] numbers) { return Arrays.stream(numbers) .filter(Objects::nonNull) // Filter out null values .sorted(Comparator.reverseOrder()) // Sort in descending order .toArray(Integer[]::new); }}
- User
sort Objects having priority integer attribute in decending order with null values in java using streams
Assistant
import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors;
public class PriorityObjectSorting { public static void main(String[] args) { List objects = Arrays.asList( new PriorityObject(7, "Object 1"), null, new PriorityObject(5, "Object 2"), new PriorityObject(3, "Object 3"), null, new PriorityObject(9, "Object 4"), new PriorityObject(1, "Object 5") );
codeList<PriorityObject> sortedObjects = sortObjectsByPriorityDescending(objects); System.out.println(sortedObjects); } public static List<PriorityObject> sortObjectsByPriorityDescending(List<PriorityObject> objects) { return objects.stream() .filter(Objects::nonNull) // Filter out null objects .sorted(Comparator.comparing(PriorityObject::getPriority) .reversed()) // Sort by priority in descending order .collect(Collectors.toList()); }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.