I have an Object of goods, which has two properties: firstCategoryId
and secondCategoryId
. I have a list of goods, and I want to get all category Ids (including both firstCategoryId and secondCategoryId).
My current solution is:
List<Integer> categoryIdList = goodsList.stream().map(g->g.getFirstCategoryId()).collect(toList());
categoryIdList.addAll(goodsList.stream().map(g->g.getSecondCategoryId()).collect(toList()));
Is there a more convenient manner I could get all the categoryIds in a single statement?
To sort on multiple fields, we must first create simple comparators for each field on which we want to sort the stream items. Then we chain these Comparator instances in the desired order to give GROUP BY effect on complete sorting behavior.
Collections. sort is a static method in the native Collections library. It does the actual sorting, you just need to provide a Comparator which defines how two elements in your list should be compared: this is achieved by providing your own implementation of the compare method.
The list of all declared fields can be obtained using the java. lang. Class. getDeclaredFields() method as it returns an array of field objects.
You can do it with a single Stream
pipeline using flatMap
:
List<Integer> cats = goodsList.stream()
.flatMap(c->Stream.of(c.getFirstCategoryID(),c.getSecondCategoryID()))
.collect(Collectors.toList());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With