Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get values of a property from array of objects [duplicate]

I have an list of objects:

[class RetailerItemVariant {
    sku: 008884303996
    isAvailable: true
    price: 70.0
}, class RetailerItemVariant {
    sku: 008884304030
    isAvailable: true
    price: 40.0
},
...

What's the best way to extract an array of the SKU's in Java 8? e.g.:

["008884303996", "008884304030", ...]

Im new to Java and this is very easy in Javascript using the map() function but I haven't been able to find a similarly simple way of doing it in Java...

like image 471
Mark Avatar asked Mar 21 '18 08:03

Mark


People also ask

How do you get a list of duplicate objects in an array of objects with JavaScript?

To get a list of duplicate objects in an array of objects with JavaScript, we can use the array methods. to get an array of value entries with the same id and put them into duplicates . To do this, we get the id s of the items with the same id by calling map to get the id s into their own array.

How do you find duplicate values in an array of objects using Lodash?

To get duplicate values from an array with Lodash, we can use the countBy method to count the values. Then we call the JavaScript array's reduce method to get all the items that has count more than 1 and put them in an array.

How do you find the index of duplicate elements in an array?

indexOf() function. The idea is to compare the index of all items in an array with an index of their first occurrence. If both indices don't match for any item in the array, you can say that the current item is duplicated. To return a new array with duplicates, use the filter() method.


2 Answers

Since you use Java 8, the stream api can help you here:

List<String> skus = itemList.stream()
          .map(Item::getSku)
          .collect(Collectors.toList());
like image 148
vahdet Avatar answered Sep 20 '22 15:09

vahdet


Also in Java 8 there are map you can use :

List<String> listSku = listRetailerItemVariant.stream()
                       .map(RetailerItemVariant::getSku)
                       .collect(toList());
like image 22
YCF_L Avatar answered Sep 22 '22 15:09

YCF_L