1. Introduction
Get all numbers greater than x where x is some number. For example, get all the numbers greater than 10.
2. Content
We will explore a few different ways to get all the numbers greater than the specified element.
3. Using for-each loop
Using for-each loop, we can filter out the values on the List, which are greater than 10 and store it in the result List.
List<Integer> numbers = Arrays.asList(56, 7, 845, 2, 3, 4, 78); List<Integer> result = new ArrayList<>(); for (Integer val : numbers) { if(val.intValue() > 10) { result.add(val); } } Assert.assertEquals(3, result.size());
4. Using Stream
We can use Stream to filter out the values greater than using a Predicate denoted by lambda expression and collecting the filtered values into the List.
List<Integer> numbers = Arrays.asList(56, 7, 845, 2, 3, 4, 78); List<Integer> result = numbers.stream() .filter(val -> val.intValue() > 10) .collect(Collectors.toList()); Assert.assertEquals(3, result.size());
5. Using primitive stream
We can use primitive Streams, such as IntStream, to filter out the values greater than using a Predicate denoted by lambda expression and collecting the filtered values into the resultant array.
int[] arr = { 56, 7, 845, 2, 3, 4, 78 }; int[] result = IntStream.of(arr) .filter(val -> val > 10) .toArray(); Assert.assertEquals(3, result.length);
6. Conclusion
In this article, we saw 3 different ways to filter elements of the List or array and populate the filtered elements into the resultant List or array. We used an example of filtering the integer values that are greater than 10.