如何根据特定元素(例如数字85)将Java数组拆分成多个新数组?
哈喽!大家好,很高兴又见面了,我是的一名作者,今天由我给大家带来一篇《如何根据特定元素(例如数字85)将Java数组拆分成多个新数组?》,本文主要会讲到等等知识点,希望大家一起学习进步,也欢迎大家关注、点赞、收藏、转发! 下面就一起来看看吧!
根据特定元素拆分java数组
本例中,要求根据元素85将数组拆分成多个新数组。为此,可以使用以下过程:
- 创建一个list,用于存储新数组。
- 创建一个临时list,用于存储当前数组中元素85之间的元素。
- 遍历数组,并在遇到元素85时,将临时list添加到主要list中并清除临时list。
- 将临时list添加到主要list作为最后一个数组。
以下java代码实现了这个过程:
import java.util.arraylist; import java.util.list; public class arraysplitter { public static void main(string[] args) { int[] arr = {85, -86, 13, 2, 99, 99, 99, 99, 98, 98, 99, 99, 99, 99, 20, 85, -86, 13, 2, 99, 99, 99, 99, 99, 99, 99, 85, 12, 85, -86, 13, 2, 99}; splitarray(arr, 85); } public static void splitarray(int[] arr, int target) { list<list<integer>> result = new arraylist<>(); list<integer> temp = new arraylist<>(); for (int i : arr) { if (i == target) { if (!temp.isempty()) { result.add(new arraylist<>(temp)); temp.clear(); } temp.add(i); } else { temp.add(i); } } result.add(temp); for (list<integer> list : result) { system.out.println(list); } } }
输出:
[85, -86, 13, 2, 99, 99, 99, 99, 98, 98, 99, 99, 99, 99, 20] [85, -86, 13, 2, 99, 99, 99, 99, 99, 99, 99] [85, 12] [85, -86, 13, 2, 99]
理论要掌握,实操不能落!以上关于《如何根据特定元素(例如数字85)将Java数组拆分成多个新数组?》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注公众号吧!