使用 Java 流将列表转换为字符串

Mam*_*ama 1 java java-8 java-stream

我创建了一个 for every 循环,并获得了价格代码列表,但我想在不使用任何循环的情况下获得相同的东西,并使用 java8 执行此操作供您参考,我发布了我的旧代码。我只想更改代码的这个位置。

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());
        }
Run Code Online (Sandbox Code Playgroud)

但我不想使用任何循环我想在不使用任何循环的情况下获得相同的结果。为了解决这个问题,我尝试了这种方法,但没有取得任何成功。

itemPriceCodes.stream().map(n -> String.valueOf(n)).collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

这是我的这个函数的完整代码

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;      
      }
Run Code Online (Sandbox Code Playgroud)

Ron*_*ain 6

它应该是

List<String> priceCodeList = itemPriceCodes.stream().map(ItemPriceCode::getPriceCode)).collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

编辑:Java 16+

List<String> priceCodeList = itemPriceCodes.stream().map(ItemPriceCode::getPriceCode)).toList()
Run Code Online (Sandbox Code Playgroud)

尽管这会返回一个不可变的列表。

进一步阅读:Java 16 的 Stream.toList() 和 Stream.collect(Collectors.toList()) 的区别?

尽管似乎没有必要考虑用例,但如果您想使用,String.valueOf()则需要toString在类中进行相应的重写,因为String.valueOf()使用它来获取字符串表示形式。

valueOf() 的定义

public static String valueOf(Object obj) {  
   return (obj == null) ? "null" : obj.toString();  
}
Run Code Online (Sandbox Code Playgroud)

因此,为了让你的代码工作......将其添加到你的类中

class ItemPriceCode{
  .
  .
  .
  public String toString(){
     return this.getPriceCode();
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 您可以进一步更改“.collect(Collectors.toList())”并将其替换为“.toList()” (3认同)