在Java 8中从列表创建字符串和对象的映射

Abh*_*ash 2 java java-8 java-stream

我有以下课程:

class Data {
        String systemId;
        String fileName;
        int x;
        int y;

        Data(String systemId, String fileName, int x, int y) {
            this.systemId = systemId;
            this.fileName = fileName;
            this.x = x;
            this.y = y;
        }
        public String getSystemId() {
            return systemId;
        }

        public void setSystemId(String systemId) {
            this.systemId = systemId;
        }

        public String getFileName() {
            return fileName;
        }

        public void setFileName(String fileName) {
            this.fileName = fileName;
        }

        public int getX() {
            return x;
        }

        public void setX(int x) {
            this.x = x;
        }

        public int getY() {
            return y;
        }

        public void setY(int y) {
            this.y = y;
        }
    }


class Result {
        int x;
        int y;

        Result(int x, int y) {
            this.x = x;
            this.y = y;
        }

        public int getX() {
            return x;
        }

        public void setX(int x) {
            this.x = x;
        }

        public int getY() {
            return y;
        }

        public void setY(int y) {
            this.y = y;
        }
    }

List<Data> dataList = new ArrayList<>();
Data x1 = new Data("n1", "f1", 1, 2);
Data x2 = new Data("n1", "f1", 3, 4);
Data x3 = new Data("n1", "f1", 5, 6);
Data x4 = new Data("n1", "f2", 7, 8);
Data x5 = new Data("n2", "f1", 9, 10);
Data x6 = new Data("n2", "f2", 11, 12);
Data x7 = new Data("n3", "f1", 13, 14);
Data x8 = new Data("n4", "f1", 15, 16);

dataList.add(x1);dataList.add(x2);dataList.add(x3);dataList.add(x4);dataList.add(x5);dataList.add(x6);dataList.add(x7);dataList.add(x8);
Run Code Online (Sandbox Code Playgroud)

我想使用Java流Map<String, List<Result>>从给定的输入列表中创建一个。另外,列表值需要根据字段(x和y)以升序排序

我需要输出映射如下:

{"n1:f1" : [(1, 2), (3, 4), (5, 6)]
 "n1:f2" : [(7, 8)]
 "n2:f1" : [(9, 10)]
 "n2:f2" : [(11, 12)]
 "n3:f1" : [(13, 14)]
 "n4:f1" : [(15, 16)]
}
Run Code Online (Sandbox Code Playgroud)

映射的键是由冒号连接的systemid和文件名的组合。我尝试通过systemid和filename的组合进行分组,但是无法继续使用该方法。

Nam*_*man 6

您可以将下游的groupingBy收集器mapping用作:

Map<String, List<Result>> map = data.stream()
        .collect(Collectors.groupingBy(a -> a.getSystemId() + ":" + a.getFileName()
                , Collectors.mapping(a -> new Result(a.getX(), a.getY()),
                        Collectors.toList())));
Run Code Online (Sandbox Code Playgroud)

  • 注意:这取决于分组键`a-&gt; a.getSystemId()+“:” + a.getFileName()`的唯一性来产生正确的结果。 (2认同)
  • @ Abhilash28Abhi并不是方法引用的工作方式。在这种情况下,方法引用代表“函数”对象,而不是方法调用的潜在结果。如果强制转换每个方法引用,则可以将它们与字符串连接起来,但这仍然不能满足您的要求(例如,尝试:`(((Function &lt;String,?&gt;)String :: format)+“: “ +((Function &lt;String,?&gt;)String :: trim)`)。将其编写为lambda表达式是可行的方法。 (2认同)