1

Suppose I have class:

class Product {
   int pId;
   String pName;
   int pPrice;
}

I have Arraylist<Product>, so can I get ArrayList<String> which contain product name only without loop.

Say with help of cursor or collection utils or any other thing in android.

Bhavesh Patadiya
  • 25,740
  • 15
  • 81
  • 107
user3322553
  • 239
  • 2
  • 8
  • 1
    How you are adding data of product in arraylist? Because if you are adding product in arraylist at that same time you will have product name which you need to add in another arraylist, i think that is the best way to do that. And if you are dealing with DB then you can directly query and get data. – Silvans Solanki Mar 17 '16 at 10:05
  • give us some more code where do you add Products to the list. – Vucko Mar 17 '16 at 10:08

2 Answers2

1

In Java 8 you can use stream and map function on the list of your products.

Assume you have:

List<Product> productList = new ArrayList<Product>();
productList.add(new Product(1, "test", 100));
productList.add(new Product(1, "test2", 100));

You can use this approach to map it to List<String>:

List<String> productNames = productList.parallelStream()
                              .map(Product::getPName)
                              .collect(toList());

Edit:

Community
  • 1
  • 1
mzy
  • 1,754
  • 2
  • 20
  • 36
0

This way might be helpful:

class Product {
    int pId;
    String pName;
    int pPrice;
}

List<Product> products = new ArrayList<>();

// add products

List<String> names = new AbstractList<String>() {
    @Override
    public String get(int location) {
        return products.get(location).pName;
    }

    @Override
    public int size() {
        return products.size();
    }
}
Victor B
  • 229
  • 3
  • 7