Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
288 views
in Technique[技术] by (71.8m points)

java - combine items of list

Hi I have a list with lets say these items {30 50 5 60 90 5 80} what I want to do is for example combine the 3rd and 4th element together and have {30 50 65 90 5 80}

Could you tell me how would I do that? I am using the java linked list class.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
public class Main {
    public static void main(String[] args) {
        List<Integer> list = new LinkedList<>();
        list.add(30);
        list.add(50);
        list.add(5);
        list.add(60);
        list.add(90);
        list.add(5);
        list.add(80);
        System.out.println(list);
        combine(list, 2, 3);
        System.out.println(list);
    }
    public static void combine(List<Integer> list, int indexA, int indexB) {
        Integer a = list.get(indexA);
        Integer b = list.get(indexB);
        list.remove(indexB); // [30, 50, 5, 90, 5, 80]
        list.add(indexA, a + b); // [30, 50, 65, 5, 90, 5, 80]
        list.remove(indexB); // [30, 50, 65, 90, 5, 80]
    }
}

The output is:

[30, 50, 5, 60, 90, 5, 80]
[30, 50, 65, 90, 5, 80]

You need check nulls values for avoid NullPointerException


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...