有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何根据元素将重复元素和不同值的字符串的一部分排序到不同的数组中?

我目前正在尝试根据元素(如freq、mag等)将以下字符串转换为几个数组。该字符串最初是json格式的,但使用Gson,它被转换为我正在使用的另一个类的对象,然后转换为字符串,以便更容易排序(对我来说)我正在寻找关于如何将其转换为字符串数组的建议,或者是否有其他更简单的方法来准备多个数组

[freq: 17.97  mag: 8.22  bw: 0.44  snr: 2.47  med: 3.33, freq: 9.96  mag: 4.06  bw: 0.41  snr: 2.31  med: 1.76, freq: 23.05  mag: 0.92  bw: 0.41  snr: 2.24  med: 0.41, freq: 12.99  mag: 1.07  bw: 0.38  snr: 2.19  med: 0.49, freq: 7.18  mag: 18.54  bw: 0.47  snr: 2.15  med: 8.61]

理想情况下,我最终会得到如下结果:

frequencyArray[0] = 17.97
frequencyArray[1] = 9.96
frequencyArray[x] = [x]

等等


共 (4) 个答案

  1. # 1 楼答案

    地图是你的朋友

    String str = "[freq: 17.97  mag: 8.22  bw: 0.44  snr: 2.47  med: 3.33, freq: 9.96  mag: 4.06  bw: 0.41  snr: 2.31  med: 1.76," +
                " freq: 23.05  mag: 0.92  bw: 0.41  snr: 2.24  med: 0.41, freq: 12.99  mag: 1.07  bw: 0.38  snr: 2.19  med: 0.49, freq: 7.18 " +
                " mag: 18.54  bw: 0.47  snr: 2.15  med: 8.61]\n";
        List<String> stringList = Arrays.asList(str.split("  |,")); // split into pair key : value
        Map<String, List<String>> map = new HashMap<>();
    
        stringList.forEach(s1 -> {
                    String[] splitedStrings = s1.split(": "); //split into key : value
                    String key = splitedStrings[0].replaceAll("[^A-Za-z0-9]",""); // remove non alphanumeric from key, like {
                    String value = splitedStrings[1];
                    if (map.get(key) == null) {
                        List<String> values = new ArrayList<>();
                        values.add(value);
                        map.put(key, values);
                    }else if (map.get(key) != null) {
                        map.get(key).add(value);
                    }
                });
        System.out.println(map);
    

    输出:

    {mag=[8.22, 4.06, 0.92, 1.07, 18.54], 
        bw=[0.44, 0.41, 0.41, 0.38, 0.47], 
        snr=[2.47, 2.31, 2.24, 2.19, 2.15], 
        freq=[17.97, 9.96, 23.05, 12.99, 7.18], 
        med=[3.33, 1.76, 0.41, 0.49, 8.61]
        ]}
    
  2. # 2 楼答案

    你可以试着把它放到这样的地图上

    我假设您的格式非常规则,两个空格分隔两个键值对,逗号分隔数据行

    key1: x.xx  key2: x.xx  key3: x.xx, key1: x.xx  key2: x.xx  key3: x.xx ...
    
    //The result
    Map<String, double[]> values = new HashMap<>();
    
    //Remove the square brackets
    input = input.substring(1, input.length() - 1);
    //Separate every freq: x.xx mag: x.xx ...
    String[] rows = input.split(", ");
    
    for (int i = 0; i < rows.length; i ++) {
      for (String s : rows[i].split("  ")) {
        //Split into "freq", "mag", etc. and the double value
        String[] keyVal = s.split(": ");
        String key = keyVal[0];
        String val = keyVal[1];
        //The first time, a new array has to be added
        if (i == 0) values.put(key, new double[rows.length]);
        //Parse the number and add it to the map
        values.get(key)[i] = Double.parseDouble(val);
      }
    }
    

    这个的输出

    for (var entry : values.entrySet()) {
      System.out.println(entry.getKey() + ": " + Arrays.toString(entry.getValue()));
    }
    

    mag: [8.22, 4.06, 0.92, 1.07, 18.54]
    bw: [0.44, 0.41, 0.41, 0.38, 0.47]
    snr: [2.47, 2.31, 2.24, 2.19, 2.15]
    freq: [17.97, 9.96, 23.05, 12.99, 7.18]
    med: [3.33, 1.76, 0.41, 0.49, 8.61]
    

    假设输入是这样定义的(忽略换行符,它们只是为了格式化,因为代码不换行)

    String input = 
    "[freq: 17.97  mag: 8.22  bw: 0.44  snr: 2.47  med: 3.33, 
    freq: 9.96  mag: 4.06  bw: 0.41  snr: 2.31  med: 1.76, 
    freq: 23.05  mag: 0.92  bw: 0.41  snr: 2.24  med: 0.41, 
    freq: 12.99  mag: 1.07  bw: 0.38  snr: 2.19  med: 0.49, 
    freq: 7.18  mag: 18.54  bw: 0.47  snr: 2.15  med: 8.61]";
    

    虽然键的顺序没有保留(如果需要,您可以使用LinkedHashMap),但内部数字的顺序是


    使用流的另一种方法:

    Map<String, List<Double>> res = Arrays
      .stream(input.split("[, ] "))
      .map(s -> s.split(": "))
      .collect(Collectors.groupingBy(s -> s[0]))
      .entrySet().stream()
      .collect(Collectors.toMap(
          e -> e.getKey(),
          e -> e.getValue()
                .stream()
                .map(ns -> Double.parseDouble(ns[1]))
                .collect(Collectors.toList())));
    

    输出

    {mag=[8.22, 4.06, 0.92, 1.07, 18.54], 
    bw=[0.44, 0.41, 0.41, 0.38, 0.47], 
    snr=[2.47, 2.31, 2.24, 2.19, 2.15], 
    freq=[17.97, 9.96, 23.05, 12.99, 7.18], 
    med=[3.33, 1.76, 0.41, 0.49, 8.61]}
    
  3. # 3 楼答案

    您可以使用Map<Integer, Double[]>存储所有数组。首先按,拆分,然后按拆分。必须进行清洁和过滤,并使用索引来知道将阀门放置在何处

    Map<Integer, Double[]> mapOfArrays = new HashMap<>();
    String[] cleanAndSplitByComma = str.replace("]", "").split(",");
    int arrayIndex = 0;
    for (String line : cleanAndSplitByComma) {
        int partIndex = 0;
        for (String value : line.split(" ")) {
            if (!value.isBlank() && !value.contains(":")) {
                mapOfArrays.computeIfAbsent(partIndex,
                        c -> new Double[cleanAndSplitByComma.length]
                )[arrayIndex] = Double.valueOf(value);
                partIndex++;
            }
        }
        arrayIndex++;
    }
    

    之后,您可以通过索引获取阵列或打印整个地图:

    Double[] frequencyArray = mapOfArrays.get(0);
    mapOfArrays.values().stream()
            .map(Arrays::asList)
            .forEach(System.out::println);
    
    [17.97, 9.96, 23.05, 12.99, 7.18]
    [8.22, 4.06, 0.92, 1.07, 18.54]
    [0.44, 0.41, 0.41, 0.38, 0.47]
    [2.47, 2.31, 2.24, 2.19, 2.15]
    [3.33, 1.76, 0.41, 0.49, 8.61]
    
  4. # 4 楼答案

    String s = "freq: 17.97  mag: 8.22  bw: 0.44  snr: 2.47  med: 3.33, freq: 9.96  mag: 4.06  bw: 0.41  snr: 2.31  med: 1.76, freq: 23.05  mag: 0.92  bw: 0.41  snr: 2.24  med: 0.41, freq: 12.99  mag: 1.07  bw: 0.38  snr: 2.19  med: 0.49, freq: 7.18  mag: 18.54  bw: 0.47  snr: 2.15  med: 8.61";
    
    Map<String, List<Float>> map = new HashMap<>();
    String[] split = s.split("\\s+");
    for (int i = 0; i < split.length; i++) {
        String a = split[i];
        if (a.contains(":")) {
            String substring = a.substring(0, a.length() - 1);
            if (map.containsKey(substring)) {
                String floatString = split[++i].trim();
                if (floatString.endsWith(",")) {
                    floatString = floatString.substring(0, floatString.length() - 1);
                }
                map.get(substring).add(Float.valueOf(floatString));
            } else {
                List<Float> list = new ArrayList<>();
                String floatString = split[++i].trim();
                if (floatString.endsWith(",")) {
                    floatString = floatString.substring(0, floatString.length() - 1);
                }
                list.add(Float.valueOf(floatString));
                map.put(substring, list);
            }
        }
    }
    
    System.out.println(map);
    

    一个MapList更适合这个问题

    输出:

    { mag=[8.22, 4.06, 0.92, 1.07, 18.54], 
      bw=[0.44, 0.41, 0.41, 0.38, 0.47], 
      snr=[2.47, 2.31, 2.24, 2.19, 2.15], 
      freq=[17.97, 9.96, 23.05, 12.99, 7.18], 
      med=[3.33, 1.76, 0.41, 0.49, 8.61]
    }
    

    我已经清理了一些字符串,比如在一些值之后删除了额外的","