You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

实现从JSON音阶数据中筛选包含指定音键的Java方法

嘿,我来帮你补全这个方法的实现逻辑,同时把内容按要求整理好~

需求概述

我们有一份存储音乐音阶与对应音键的JSON数据,需要实现一个方法:接收音键列表作为参数,返回所有包含这些音键的音阶名称。

JSON数据示例

{ 
  "allScalesJson": [ 
    { 
      "scale": "A Major", 
      "keys": [ "b", "a", "e", "d", "gs", "fs", "cs" ] 
    }, 
    { 
      "scale": "B Major", 
      "keys": [ "b", "e", "as", "gs", "fs", "ds", "cs" ] 
    }, 
    { 
      "scale": "D Major", 
      "keys": [ "b", "a", "g", "e", "d", "fs", "cs" ] 
    } 
  ] 
}

示例调用与输出

调用代码:

List<String> returned_scales = findScalesThatContainThisKeys(Arrays.asList("a","d"));

输出结果:

A Major, D Major

补全后的完整方法实现
private List<String> findScalesThatContainThisKeys(List<String> keys_array){ 
    List<String> foundedScales = new ArrayList<>(); 
    try { 
        JSONObject jsonObj = new JSONObject(loadJSONFromAsset()); 
        JSONArray rootElement = jsonObj.getJSONArray("allScalesJson"); 
        for (int i = 0; i < rootElement.length(); i++) { 
            JSONObject obj = rootElement.getJSONObject(i); 
            String scale = obj.getString("scale"); 
            // Keys is json array 
            JSONArray genreArray = obj.getJSONArray("keys"); 
            ArrayList<String> keys = new ArrayList<>(); 
            for (int j = 0; j < genreArray.length(); j++) { 
                // 提取当前音阶的所有音键到列表中
                keys.add(genreArray.getString(j)); 
            }
            // 判断当前音阶是否包含传入的所有音键
            if (keys.containsAll(keys_array)) {
                foundedScales.add(scale);
            }
        } 
    }catch (Exception e){
        e.printStackTrace(); 
    } 
    return foundedScales; 
}

关键逻辑说明

  • 内层循环:将JSON数组中的每个音键字符串提取出来,存入keys列表,方便后续判断;
  • 核心判断:利用List.containsAll()方法,检查传入的音键列表是否是当前音阶音键列表的子集——也就是当前音阶是否包含所有传入的音键;
  • 结果收集:如果满足条件,就把该音阶名称加入结果列表foundedScales。

内容的提问来源于stack exchange,提问作者Mehran

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:30:49