[참고] Stream 정리

MARCH 21, 2021

#. Convert String[] to Stream

Arrays.asList(new String[]{"aa", "bb"}).stream()

int[] to Stream

  • boxed() : intStream 을 Stream 로 변경
int[] arr = new int[]{1,3,5,7,9,2,4,6,8,1,3,5,7,9,2};

int[] result = IntStream.of(arr)
    .distinct().toArray();

List<Integer> result = IntStream.of(arr)
    .distinct().boxed()
    .collect(Collectors.toList());

to String[]

Arrays.stream(new String[]{"aaa", "abc", "ccc", "add"})
    .toArray(String[]::new);

to int[]

List<Integer> list = new ArrayList<>();
list.stream().mapToInt(i->i).toArray();

List<List<Integer>> to int[][]

List<List<Integer>> result;
result.stream()
    .map(r -> r.stream().mapToInt(i -> i).toArray())
    .toArray(int[][]::new);

to Map

  • to map
Map<String, String> input = new HashMap<>() {{
    put("string1", "41");
    put("string2", "42");
}};

Map<String, String> collect = input.entrySet().stream()
    .map(entry -> {
        //  Map.Entry<String, String> newEntry = new AbstractMap.SimpleEntry(entry.getKey(), entry.getValue());
        Map.Entry<String, String> newEntry = Map.entry(entry.getKey(), entry.getValue());
        return newEntry;
    })
    .collect(Collectors.toMap(
        entry -> entry.getKey(),
        entry -> entry.getValue()
    ));
  • to LinkedHashMap
.collect(Collectors.toMap(
    e -> e.getKey(),
    e -> e.getValue(),
    (x,y) -> y,
    LinkedHashMap::new
));
  • use Function
public static <X, Y, Z> Map<X, Z> transform(Map<X, Y> input, Function<Y, Z> function) {
    return input.entrySet().stream()
      .collect(Collectors.toMap(
           (entry) -> entry.getKey(),
           (entry) -> function.apply(entry.getValue())
      ))
    ;
}

Map<String, String> input = new HashMap<String, String>() {{
     put("string1", "41");
     put("string2", "42");
}};
Map<String, Integer> output = transform(input, val -> Integer.parseInt(val));

#. Sort AES

IntStream.of(14, 11, 20, 39, 23)
    .sorted()
    .boxed()
    .collect(Collectors.toList());
[11, 14, 20, 23, 39]

DESC

IntStream.of(14, 11, 20, 39, 23)
    .sorted(Comparator.reverseOrder())
    .boxed()
    .collect(Collectors.toList());
// [39, 23, 20, 14, 11]

Custom

Arrays.asList(new String[]{"abce", "abcd", "cdx"}).stream()
    .sorted((string1, string2) -> {
        int result = string1.charAt(n) - string2.charAt(n);
        if(result == 0)
            return string1.compareTo(string2);
        return result;
    })
    .toArray(String[]::new);
// input : ["abce", "abcd", "cdx"], n:2
// output : ["abcd", "abce", "cdx"]

문자열 정렬

  • sort 사용 시 Comparator 는 객체만 가능, primitive 는 불가능
  • 따라서 char[] 는 재정의된 sort 사용 불가능
  • char 를 객체로 변경해야 함
String targetStr = "abcdefABC";
String result = targetStr.chars().mapToObj(String::valueOf)
    .sorted(Collections.reverseOrder())
    .collect(Collectors.joining());

// StringBuilder 로 리턴
targetStr.chars().mapToObj(item -> (char)item)
    .sorted(Comparator.reverseOrder())
    .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
    .toString();

Grouping


작업 기록 블로그