How to create HashSet from List<Object> by taking multiple field values from object with Java8 Stream?

027 :

DataHistoryRecord class:

public class DataHistoryRecord {

Long dataCreatedBy;
Long dataModifiedBy;
getters & setters

}

I have List<DataHistoryRecord> and i want to create HashSet from it with unique dataCreatedBy and dataModifiedBy id.

For example : If list has following two records:

DataHistoryRecord1 with dataCreatedBy: 1 and dataModifiedBy: 2

DataHistoryRecord2 with dataCreatedBy: 1 and dataModifiedBy: 3

Output HashSet should have three values; 1,2,3

Note : Please suggest approach without foreach

Ravindra Ranwala :

You may do it like so,

Set<Long> uniqueValues = historyRecords.stream()
        .flatMap(hr -> Stream.of(hr.getCreatedBy(), hr.getModifiedBy()))
        .collect(Collectors.toSet());

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=87088&siteId=1