有 Java 编程相关的问题?

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

java建议汇总列表中的值

我有一个字符串列表,如下所示:

"AB", "XY", 10
"CD", "XY", 15
"CD", "XY", 12
"AB", "XY", 19

我要做的是将最后一个值中的数字与第一个值相加,并将其放入一个新列表中

因此,这将给我:

"AB", "XY", 29
"CD", "XY", 27

我是Java新手,所以我还在为语法和不同的方法而挣扎。我查看了compareTo()和equals()方法,但是很遗憾。我需要一些帮助


共 (2) 个答案

  1. # 1 楼答案

    第一个问题是:为什么要将其作为字符串列表?看起来您有一个包含3个属性的对象列表:2个字符串和一个整数。拥有这样的数据结构将使代码更易于读写

    现在,为了解决这个问题,您首先需要制作一个映射来保存字符串的第一部分和数字的总和:

    1. 使用流API,通过使用Collectors.groupingBy收集器创建映射,该收集器将每个字符串分类为字符串的第一部分,即最后一个逗号之前的所有内容。然后,对于分类到同一个键的所有值,我们使用Collectors.summingInt对最后一个逗号后面的数字求和
    2. 当我们有了这个映射之后,我们可以迭代它的所有条目,并将每个条目转换回一个String,最后将其收集到一个带有Collectors.toList()的列表中

    示例代码:

    public static void main(String[] args) {
        List<String> list = Arrays.asList("\"AB\", \"XY\", 10", "\"CD\", \"XY\", 15", "\"CD\", \"XY\", 12", "\"AB\", \"XY\", 19");
    
        Map<String, Integer> map =
            list.stream()
                .collect(Collectors.groupingBy(
                    s -> s.substring(0, s.lastIndexOf(',')),
                    Collectors.summingInt(s -> Integer.parseInt(s.substring(s.lastIndexOf(',') + 2)))
                ));
        List<String> result =
            map.entrySet()
               .stream()
               .map(e -> e.getKey() + ", " + e.getValue())
               .collect(Collectors.toList());
    
        System.out.println(result);
    }
    
  2. # 2 楼答案

    输入数据:

    "AB", "XY", 10
    "CD", "XY", 15
    "CD", "XY", 12
    "AB", "XY", 19
    "AB", "XY", 3
    

    代码:

    String inputData = "\"AB\", \"XY\", 10\n\"CD\", \"XY\", 15\n\"CD\", \"XY\", 12\n\"AB\", \"XY\", 19\n\"AB\", \"XY\", 3";
    
    final String[] lines = inputData.split("\\n");
    
    Map<String,Integer> results = new HashMap<>();
    
    final Pattern compiledPattern = Pattern.compile("([\\\"A-Z,\\s]+),\\s(\\d+)");
    
    for (String line : lines) {
        final Matcher matcher = compiledPattern.matcher(line);
    
        if (matcher.matches()) {
            final String groupName = matcher.group(1);
            final int value = Integer.valueOf(matcher.group(2));
    
            if (results.containsKey(groupName)) {
                final Integer currentValue = results.get(groupName);
    
                results.put(groupName, (currentValue+value));
        } else {
            results.put(groupName, value);
        }
    }
    

    我的数据的输出:

    "CD", "XY" > 27
    "AB", "XY" > 32