else梯形图

hs1ihplo  于 2021-06-30  发布在  Java
关注(0)|答案(2)|浏览(289)

我正在吃 ArrayStrings 以…的形式

[field1, Expected: 60,got: 70,field2, Expected: 80,got: 90, field3, Expected: 90,got: 70]

从这个 array 我正在把它构造成 List<HashMap<String,String>> 这是我到目前为止试过的

List<HashMap<String,String>> getErroMap(String [] err){
    List<HashMap<String,String>> listErrorMap = new ArrayList<HashMap<String,String>>();
    HashMap<String,String> errorMap=null;
    byte count = 0;
    for (String arr : err) {
        if(count == 0 ) {
             errorMap = new HashMap<String, String>();
             errorMap.put("object",arr.replaceAll(".import", ""));
        }else if (count >0) {
            String key = count ==1?"Expected":"Found";
            if(arr.contains(":")) {
                 String[] tokens = arr.split(":");
                 errorMap.put(key, tokens[1]);
            }else {
                 errorMap.put(key, arr);
            }
        }
        if(count >= 2) {
            listErrorMap.add(errorMap);
            count = 0 ;
        }else {
            count++;
        }
    }
    return listErrorMap;
}

并得到期望的输出

[{'object':field1,"Expected":60,"Found":70},{'object':'field2','Expected':80,'Found':90  ..and so on ]

因为我是新来的 Java 8 我想我做了很多代码来实现简单的事情。如何使用 java 8 .

ncgqoxb0

ncgqoxb01#

为了得到你想要的结果,你需要返回 List<List<HashMap<String,String>>> ,这不是理想的清洁。
最好按照建议创建一个自定义类,然后创建 List<CustomClass> . 例如:

public class myClass{
    public String obj;
    public int expected;
    public int found;

    public myClass(String obj, int expected, int found){
        this.obj = obj;
        this.expected = expected;
        this.found = found;
    }
}

然后,您可以创建一个循环:

private List<myClass> convertToMap(String[] info){
    ArrayList<myClass> newList = new ArrayList<myClass>();
    for(int i = 0; i < info.length; i += 3){
        if(i < info.length){
          newList.add(new myClass(info[i],
                      Integer.parseInt(info[i+1]), 
                      Integer.parseInt(info[i+2])));
        }
    }
    return newList;
}
z18hc3ub

z18hc3ub2#

下面是你想要的?

private List<Map<String, String>> getErrorMap(String[] inputs) {
    if (inputs.length % 3 != 0) {
        return new ArrayList<>();
    }
    final AtomicInteger counter = new AtomicInteger(0);
    return Arrays.stream(inputs)
        .collect(Collectors.groupingBy(s -> counter.getAndIncrement() / 3))
        .values()
        .stream()
        .map(strings -> {
            Map<String, String> map = new HashMap<>();
            map.put("object", strings.get(0));
            map.put("Expected", strings.get(1).split(":")[1]);
            map.put("Found", strings.get(2).split(":")[1]);
            return map;
        }).collect(Collectors.toList());
}

输入:

{"field1", "Expected: 60", "got: 70", "field2", "Expected: 80", "got: 90", "field3", "Expected: 90", "got: 70"}

输出:

[{Expected= 60, Found= 70, object=field1}, {Expected= 80, Found= 90, object=field2}, {Expected= 90, Found= 70, object=field3}]

相关问题