简体   繁体   中英

Merge elements of a list to a single element in java arraylist

I have an arraylist of String.

List<String> list = new ArrayList<>();

I have added 2 elements to the list.

list.add("text1");
list.add("text2");

The output is like this.

[text1,text2]

But I need an output as below.

[text1 text2]

ie, both elements should be merged and placed in a single index. Could someone help on this?

To everyone who didn't read the question completely, this is the last sentence: "both elements should be merged and placed in a single index".

You can just create the merged String and create a new List with one entry:

List<String> result = List.of(list.stream().collect(Collectors.joining(" ")));

If you need to reduce the existing List down to one element, you can keep adding each subsequent element to the first one using this loop:

list.add("text1");
list.add("text2");
list.add("text3");
list.add("text4");
while(list.size() > 1) {
    list.set(0, list.get(0) +" "+ list.remove(1));
}
System.out.println(list);

prints [text1 text2 text3 text4]

You can do it like this.

    List<String> list = new ArrayList<>();
    list.add("text1");
    list.add("text2");

    list.set(0, String.join(",", list).replace(",", " "));

    list.subList(1, list.size()).clear();

    System.out.println(list.size());
    System.out.println(list);

Output of this is:

1

[text1 text2]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM