Create List of Object from Another Using Java 8 Streams

Create a list of objects from another list using Java 8 streams

You can do it with a custom collect(I added getters and some obvious constructors):

Map<String, OrganismeDTO> map = dt.stream().collect(HashMap::new, (m, t) -> {
m.computeIfAbsent(t.getOrganismeLib(), x -> new OrganismeDTO(t.getOrganismeLib())).getRolesDTO().add(new RoleDTO(t.getRoleLib()));
}, (m1, m2) -> {
m2.forEach((k,v) -> {
OrganismeDTO organismeDTO = m1.get(k);
if (organismeDTO != null ) {
organismeDTO.getRolesDTO().addAll(v.getRolesDTO());
} else {
m1.put(k, v);
}
});
});

And then all that's left if to create List from the values.

List<OrganismeDTO> list = map.values().stream().collect(Collectors.toList());

Java : use Streams to convert List<Object> to another List<anotherObject>

You can use the Collectors.mapping along with groupingBy of samples(Sample instead of Object) to get an intermediate state of List<User> with the id they are associated to and them map each such entry to a ResultObject as:

List<ResultObject> resultObjects = samples.stream()
.collect(Collectors.groupingBy(Sample::getId,
Collectors.mapping(a -> new User(a.getUserName(), a.getAddress(), a.getEmail()),
Collectors.toList())))
.entrySet().stream()
.map(e -> new ResultObject(e.getKey(), e.getValue()))
.collect(Collectors.toList());

Java 8 streams: getting lists of objects by property inside of an object in the object

It seems you want something like this:

List<User> result =  usersList.stream()
.filter(user -> user.getBasket().getApplianceList().stream()
.anyMatch(appliance ->
appliance.getApplianceName().equals("something1")))
.collect(Collectors.toList());

How to convert list of object to another list object using streams?

Simple use map() method in stream api and collect results:

  List<Emp> employe = Arrays.asList(new Emp(1, 100), new Emp(2, 200), new Emp(3, 300));
List<Emp> employeRise = employe.stream()
.map(emp -> new Emp(emp.getId(), emp.getSalary * 100))
.collect(Collectors.toList());
employeRise.stream()
.forEach(s -> System.out.println("Id :" + s.getId() + " Salary :" + s.getSalary()));

Fetch List of object from another list using java 8

Stream the contents, map to get the state and collect it as a List.

customers.stream()
.map(Customer::getState)
.collect(Collectors.toList());

If you need an ArrayList as the resultant list

customers.stream()
.map(Customer::getState)
.collect(Collectors.toCollection(ArrayList::new));


Related Topics



Leave a reply



Submit