Get property values ​​from an array of objects

I have a list of objects:

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

What is the best way to extract an SKU array in Java 8? eg:.

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

I am new to Java and it is very simple in Javascript using the map () function, but I could not find a similarly simple way to do this in Java ...

+4
source share
4 answers

Since you are using Java 8, it stream apican help you:

List<String> skus = itemList.stream()
          .map(Item::getSku)
          .collect(Collectors.toList());
+6
source

Try with java 8 thread:

List<String> listSku = list.stream().map(r->r.getSku())
                        .collect(Collectors.toList())
+2
source

Java 8 map :

List<String> listSku = listRetailerItemVariant.stream()
                       .map(RetailerItemVariant::getSku)
                       .collect(toList());
+2

, :

mylist
     .stream()
     .map(variant -> variant.getSku())
     .collect(Collectors.toCollection(ArrayList::new)))

As an initial structure, if you use arrays instead of collections, go from myList.streamto Stream.of(variantArray).map().

As for your final structure, adjust if ArrayList::newyou need HashSet ( HashSet::new) or linked list ( LinkedList::new) instead

and if you have many different options, and you want to quickly and quickly assemble them Skus, consider parallel processing of the stream, adding parallel()to the function stream():

mylist
     .stream()
     .parallel() // for parallel processing
     .map(variant -> variant.getSku())
0
source

Source: https://habr.com/ru/post/1695143/


All Articles