Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to collect two fields of an object into the same list?

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?

like image 270
zhuguowei Avatar asked Nov 09 '15 06:11

zhuguowei


People also ask

How to sort a list by two fields in Java?

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.

How to sort by 2 parameters in Java?

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.

How do I get the field list of objects?

The list of all declared fields can be obtained using the java. lang. Class. getDeclaredFields() method as it returns an array of field objects.


1 Answers

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());
like image 99
Eran Avatar answered Sep 28 '22 05:09

Eran