programing

Java 8을 사용하여 객체 목록을 toString () 메소드에서 얻은 문자열로 변환

new-time 2020. 5. 25. 21:48
반응형

Java 8을 사용하여 객체 목록을 toString () 메소드에서 얻은 문자열로 변환


Java 8에는 유용한 새로운 것들이 많이 있습니다. 예를 들어, 객체 목록을 스트림으로 반복 한 다음 Object인스턴스 의 특정 필드에서 값을 합칠 수 있습니다. 예 :

public class AClass {
  private int value;
  public int getValue() { return value; }
}

Integer sum = list.stream().mapToInt(AClass::getValue).sum();

따라서 인스턴스 StringtoString()메소드 출력을 한 줄로 묶는 메소드 를 빌드 할 수있는 방법이 있는지 묻고 있습니다.

List<Integer> list = ...

String concatenated = list.stream().... //concatenate here with toString() method from java.lang.Integer class

그 가정 list정수를 포함 1, 2그리고 3내가 그 기대 concatenated이다 "123""1,2,3".


간단한 방법 중 하나는 목록 항목을 StringBuilder

   List<Integer> list = new ArrayList<>();
   list.add(1);
   list.add(2);
   list.add(3);

   StringBuilder b = new StringBuilder();
   list.forEach(b::append);

   System.out.println(b);

당신은 또한 시도 할 수 있습니다 :

String s = list.stream().map(e -> e.toString()).reduce("", String::concat);

설명 : map은 정수 스트림을 문자열 스트림으로 변환 한 다음 모든 요소의 연결로 축소되었습니다.

참고 : 이것은 normal reductionO (n 2 ) 에서 수행됩니다.

더 나은 성능을 사용 A에 대한 StringBuilder또는 mutable reductionF. BOLLER의 대답과 비슷.

String s = list.stream().map(Object::toString).collect(Collectors.joining(","));

참조 : 스트림 감소


joiningAPI에 수집기가 있습니다 . 의 정적 메소드입니다 Collectors.

list.stream().map(Object::toString).collect(Collectors.joining(","))

의 호출로 인해 완벽 toString하지는 않지만 작동합니다. 다른 구분 기호가 가능합니다.


Java 8 없이이 작업을 수행하려는 경우를 대비하여 꽤 좋은 트릭이 있습니다. List.toString ()은 이미 다음과 같은 컬렉션을 반환합니다.

[1,2,3]

특정 요구 사항에 따라 목록 항목에 [] 또는,을 포함하지 않는 한 원하는대로 사후 처리 할 수 ​​있습니다.

예를 들어 :

list.toString().replace("[","").replace("]","") 

또는 데이터에 대괄호가 포함될 수있는 경우 :

String s=list.toString();
s = s.substring(1,s.length()-1) 

꽤 합리적인 출력을 얻을 수 있습니다.

각 라인에 하나의 배열 항목을 다음과 같이 만들 수 있습니다.

list.toString().replace("[","").replace("]","").replaceAll(",","\r\n")

이 기술을 사용하여 작은 앱의 목록에서 HTML 툴팁을 다음과 같이 만들었습니다.

list.toString().replace("[","<html>").replace("]","</html>").replaceAll(",","<br>")

배열이 있으면 대신 Arrays.asList (list) .toString ()으로 시작하십시오.

나는 이것이 최적이 아니라는 사실을 전적으로 소유 할 것이지만, 생각하는 것만 큼 비효율적이지는 않으며 읽고 이해하기가 매우 간단합니다. 그러나 융통성이 없습니다. 특히 데이터에 쉼표가 포함되어 있으면 replaceAll로 요소를 분리하지 말고 데이터에 대괄호가 있으면 하위 문자열 버전을 사용하십시오.하지만 숫자 배열은 거의 완전한.


다른 답변은 괜찮습니다. 그러나 Collectors.toList () 를 매개 변수로 Stream.collect ()에 전달하여 요소를 ArrayList로 반환 할 수도 있습니다 .

System.out.println( list.stream().map( e -> e.toString() ).collect( toList() ) );

List<String> list = Arrays.asList("One", "Two", "Three");
    list.stream()
            .reduce("", org.apache.commons.lang3.StringUtils::join);

또는

List<String> list = Arrays.asList("One", "Two", "Three");
        list.stream()
                .reduce("", (s1,s2)->s1+s2);

This approach allows you also build a string result from a list of objects Example

List<Wrapper> list = Arrays.asList(w1, w2, w2);
        list.stream()
                .map(w->w.getStringValue)
                .reduce("", org.apache.commons.lang3.StringUtils::join);

Here the reduce function allows you to have some initial value to which you want to append new string Example:

 List<String> errors = Arrays.asList("er1", "er2", "er3");
            list.stream()
                    .reduce("Found next errors:", (s1,s2)->s1+s2);

StringListName = ObjectListName.stream().map( m -> m.toString() ).collect( Collectors.toList() );


Can we try this.

public static void main(String []args){
        List<String> stringList = new ArrayList<>();
        for(int i=0;i< 10;i++){
            stringList.add(""+i);
        }
        String stringConcated = String.join(",", stringList);
        System.out.println(stringConcated);

    }

String actual = list.stream().reduce((t, u) -> t + "," + u).get();

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<Long, List<Long>> builds a json string, using list.stream().map([...]:

if (mapSize > 0) {
    StringBuilder sb = new StringBuilder("[");

    for (Map.Entry<Long, List<Long>> 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<Long, List<Long>> 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());
}

With Java 8+

String s = Arrays.toString(list.stream().toArray(AClass[]::new));

Not the most efficient, but it is a solution with a small amount of code.


Also, you can do like this.

    List<String> list = Arrays.asList("One", "Two", "Three");
    String result = String.join(", ", list);
    System.out.println(result);

참고URL : https://stackoverflow.com/questions/24882927/using-java-8-to-convert-a-list-of-objects-into-a-string-obtained-from-the-tostri

반응형