Using Java 8 to convert a list of objects into a string obtained from the toString() method

前端 未结 13 1794
太阳男子
太阳男子 2020-11-28 02:02

There are a lot of useful new things in Java 8. E.g., I can iterate with a stream over a list of objects and then sum the values from a specific field of the Object

13条回答
  •  迷失自我
    2020-11-28 02:27

    Testing both approaches suggested in Shail016 and bpedroso answer (https://stackoverflow.com/a/24883180/2832140), the simple StringBuilder + append(String) within a for loop, seems to execute much faster than list.stream().map([...].

    Example: This code walks through a Map> builds a json string, using list.stream().map([...]:

    if (mapSize > 0) {
        StringBuilder sb = new StringBuilder("[");
    
        for (Map.Entry> entry : threadsMap.entrySet()) {
    
            sb.append("{\"" + entry.getKey().toString() + "\":[");
            sb.append(entry.getValue().stream().map(Object::toString).collect(Collectors.joining(",")));
        }
        sb.delete(sb.length()-2, sb.length());
        sb.append("]");
        System.out.println(sb.toString());
    }
    

    On my dev VM, junit usually takes between 0.35 and 1.2 seconds to execute the test. While, using this following code, it takes between 0.15 and 0.33 seconds:

    if (mapSize > 0) {
        StringBuilder sb = new StringBuilder("[");
    
        for (Map.Entry> entry : threadsMap.entrySet()) {
    
            sb.append("{\"" + entry.getKey().toString() + "\":[");
    
            for (Long tid : entry.getValue()) {
                sb.append(tid.toString() + ", ");
            }
            sb.delete(sb.length()-2, sb.length());
            sb.append("]}, ");
        }
        sb.delete(sb.length()-2, sb.length());
        sb.append("]");
        System.out.println(sb.toString());
    }
    

提交回复
热议问题