1

I created a for each loop and I get list of price code but I want to get same things without using any loop and perform this operation using java8 for your reference I post my old code. I want to change only this position of my code.

List<ItemPriceCode> itemPriceCodes = item.getItemPriceCodes(); List<String> priceCodeList = new ArrayList<String>(); for (ItemPriceCode ipc : itemPriceCodes) { //get the string value from the list priceCodeList.add(ipc.getPriceCode()); } 

But I do not want to use any loop I want to get same result without using any loop . To over come from this issue I try this way but I am not get any success.

itemPriceCodes.stream().map(n -> String.valueOf(n)).collect(Collectors.toList()); 

Here This is my full code of this function

private Item getItemManufacturerPriceCodes(Item item) { List<ItemPriceCode> itemPriceCodes = item.getItemPriceCodes(); List<String> priceCodeList = new ArrayList<String>(); for (ItemPriceCode ipc : itemPriceCodes) { //get the string value from the list priceCodeList.add(ipc.getPriceCode()); } //pass this string value in query List<ManufacturerPriceCodes>mpc = manufacturerPriceCodesRepository. findByManufacturerIDAndPriceCodeInAndRecordDeleted(item.getManufacturerID(),priceCodeList,NOT_DELETED); //Convert list to map Map<String, ManufacturerPriceCodes> ipcToMFPNameMap = mpc.stream().collect( Collectors.toMap(ManufacturerPriceCodes :: getPriceCode,Function.identity()));// Object for (ItemPriceCode ipcs : itemPriceCodes) { ipcs.setManufacturerPriceCode(ipcToMFPNameMap.getClass().getName()); } item.getItemPriceCodes() .removeIf(ipcs -> DELETED.equals(ipcs.getRecordDeleted())); return item; } 
0

1 Answer 1

6

It should be

List<String> priceCodeList = itemPriceCodes.stream().map(ItemPriceCode::getPriceCode)).collect(Collectors.toList()); 

EDIT: Java 16+

List<String> priceCodeList = itemPriceCodes.stream().map(ItemPriceCode::getPriceCode)).toList() 

Although this would return an immutable list.

Furthur reading: Differences of Java 16's Stream.toList() and Stream.collect(Collectors.toList())?

Although it doesn't seem necessary considering the use case if you want to use String.valueOf() you need to override toString accordingly in your class, as String.valueOf() uses it to get the string representation.

Definition of valueOf()

public static String valueOf(Object obj) { return (obj == null) ? "null" : obj.toString(); } 

Thus to make your code work.. add this in your class

class ItemPriceCode{ . . . public String toString(){ return this.getPriceCode(); } } 
Sign up to request clarification or add additional context in comments.

1 Comment

You can go further and change the .collect(Collectors.toList()) and replace it with .toList()

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.