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...
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.
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.
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.
Since you use Java 8, the stream api
can help you here:
List<String> skus = itemList.stream()
.map(Item::getSku)
.collect(Collectors.toList());
Also in Java 8 there are map
you can use :
List<String> listSku = listRetailerItemVariant.stream()
.map(RetailerItemVariant::getSku)
.collect(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