JAVA怎样比较本集合元素?

qq_28484955 2021-03-19 11:30:43
JAVA同集合中怎样比较相邻两个元素? 例如:集合有1,5,7,9 2,4,5,9 ,2,3,5,7 2,3,5,7 2,6,7,9 4,6,8,9 2,3,5,7 2,6,7,9 2,6,7,9九个数组。 比较后为:1,5,7,9 2,4,5,9 2,3,5,7 2,6,7,9 4,6,8,9 2,3,5,7 2,6,7,9 七个数组。再查间隔多少个数组。1,5,7,9后面没有,就是6个。2,3,5,7中间有2个,就是2!
...全文
151 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
KeepSayingNo 2021-03-22
  • 打赏
  • 举报
回复
你可以把数组转换成用某个特殊字符作为分割的字符串,然后再进行比较
lin351550660 2021-03-22
  • 打赏
  • 举报
回复
import cn.hutool.json.JSONUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Test {
    public static void main(String[] args) {
        Integer[][] aa = new Integer[][]{{1,5,7,9},{2,4,5,9 },{2,3,5,7 },{2,3,5,7 },{2,6,7,9 },{4,6,8,9 },{2,3,5,7 },{2,6,7,9 },{2,6,7,9 }};
        Integer[] pre = null;
        List<Integer[]> list = new ArrayList<>();
        for (Integer[] a:aa) {
            if (pre != null){
                if (JSONUtil.toJsonStr(pre).equals(JSONUtil.toJsonStr(a))){
                    //与上一个相同
                } else {
                    list.add(a);
                }
            } else {
                list.add(a);
            }
            pre = a;
        }
        int index = 0;
        Map<String,Integer> map = new HashMap<>();
        System.out.println(JSONUtil.toJsonStr(list));
        for (Integer[] a:list ) {
            Integer integer = map.get(JSONUtil.toJsonStr(a));
            if (integer  == null){
                map.put(JSONUtil.toJsonStr(a),7-++index);
            } else {
                map.put(JSONUtil.toJsonStr(a),integer - 7 + index );
                index++;
            }
        }
        System.out.println(JSONUtil.toJsonStr(map));
    }

}

50,528

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧