简体   繁体   中英

Adding multiple Arraylist items into one ArrayList item

I have two ArrayLists and want to put a range of 5 items into one item from one ArrayList into the other. My current code for that looks like this:

fragenArrayPack.add(fragenArray.get(0) + fragenArray.get(1) + fragenArray.get(2) + fragenArray.get(3) + fragenArray.get(4));
fragenArrayPack.add(fragenArray.get(5) + fragenArray.get(6) + fragenArray.get(7) + fragenArray.get(8) + fragenArray.get(9));

This works but is very impractical. Is there a faster/better way to do this?

Why you want to add them with "+". May be you will create constructor with 5 objects or simply add with for loop

You want something like that

public int sumRangeOfArrayList(int startIndex, int lastIndex, ArrayList<Integer> myNumberArrayList) {
    if (startIndex < 0 || lastIndex < 0 || startIndex > myNumberArrayList.size() - 1 || lastIndex > myNumberArrayList.size() - 1 || startIndex > lastIndex) {
        throw new RuntimeException("wrong input");
    }
    int sum = 0;
    for (int i = startIndex; i <= lastIndex; i++) {
        sum += myNumberArrayList.get(i);
    }
    return sum;
}

Beware I did not test my code, I have just put it together. But you want a method like that, which will calculate the sum and is reusable.

Assuming your lists contains Integer and you are using Java 8, you can use streams:

public static Integer addRange(ArrayList<Integer> list, Integer startingIndex, Integer amount) {
    return list.stream().skip(startingIndex).limit(amount).reduce(0, Integer::sum);
}

fragenArrayPack.add(addRange(fragenArray, 0, 5));
fragenArrayPack.add(addRange(fragenArray, 5, 5));

For String concatenation :

public static String concatRange(ArrayList<String> list, Integer startingIndex, Integer amount) {
    return list.stream().skip(startingIndex).limit(amount).reduce("", String::concat);
}

fragenArrayPack.add(concatRange(fragenArray, 0, 5));
fragenArrayPack.add(concatRange(fragenArray, 5, 5));

And if you want you can parameterize the function to pass to the reduce method and made the method generic

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