java 流:将附加字符串收集到现有的 StringBuilder 中

问题描述 投票:0回答:2

这是我的相关代码:

  public String build() {
    StringBuilder s3Key = new StringBuilder();

    if (bucketName == null || fileName == null) {
      throw new IllegalStateException("Bucket name and file name are required");
    }

    s3Key.append(bucketName);

    String prefix = paths.stream().filter(Predicate.not(Strings::isNullOrEmpty)).collect(Collectors.joining("/"));
    s3Key.append(prefix);

    s3Key.append(fileName);

    return s3Key.toString();
  }

有没有办法将流式字符串收集到现有的

s3Key
StringBuilder

java java-stream
2个回答
0
投票

像这样尝试一下。

final StringBuilder sb = new StringBuilder("This is a test");

String[] str = {" to", " append", " more", " information."};
Arrays.stream(str).reduce(sb, (a,b)->a.append(b), (a,b)->a);

System.out.println(sb);

打印

This is a test to append more information.

您还可以执行以下操作:

sb.append(Arrays.stream(str).collect(Collectors.joining()));        

0
投票

您甚至根本不需要使用字符串生成器。只需在前面加上存储桶名称并附加文件名后,用正斜杠将各部分连接起来即可。

import java.util.List;
import java.util.stream.Collectors;
import lombok.Data;

@Data
public class S3Resource {
    private String bucketName;
    private String fileName;
    private List<String> paths;

    public String build() {
        if (!StringUtils.hasText(bucketName) || !StringUtils.hasText(fileName)) {
            throw new IllegalStateException("Bucket name and file name are required");
        }

        // Collect all valid paths into a single list
        List<String> validPaths = paths.stream()
                .filter(StringUtils::hasText)
                .collect(Collectors.toList());
        validPaths.addFirst(bucketName);
        validPaths.addLast(fileName);

        return String.join("/", validPaths);
    }

    public static void main(String[] args) {
        S3Resource resource = new S3Resource();
        resource.setBucketName("my-bucket");
        resource.setFileName("my-file.txt");
        resource.setPaths(List.of("path1", "path2"));

        System.out.println(resource.build()); // my-bucket/path1/path2/my-file.txt
    }

    static class StringUtils {
        public static boolean hasText(String s) {
            return s != null && !s.isEmpty();
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.