001package com.box.sdk.internal.utils; 002 003import java.util.ArrayList; 004import java.util.Collection; 005import java.util.LinkedList; 006import java.util.List; 007import java.util.Map; 008import java.util.stream.Collectors; 009 010/** {@link Collection} related utlities. */ 011public class CollectionUtils { 012 013 /** Only static members. */ 014 protected CollectionUtils() {} 015 016 /** 017 * Re-maps a provided collection. 018 * 019 * @param <T_Result> type of result 020 * @param <T_Source> type of source 021 * @param source for mapping 022 * @param mapper element mapper 023 * @return mapped source 024 */ 025 public static <T_Result, T_Source> List<T_Result> map( 026 Collection<T_Source> source, Mapper<T_Result, T_Source> mapper) { 027 List<T_Result> result = new LinkedList<T_Result>(); 028 for (T_Source element : source) { 029 result.add(mapper.map(element)); 030 } 031 return result; 032 } 033 034 /** 035 * Creates list from iterable. 036 * 037 * @param iterable Iterable that will be used to create list. 038 * @param <T> Collection element 039 * @return List with all items from iterable. Elements are in the same order as iterable is 040 * returning them. 041 */ 042 public static <T> List<T> createListFrom(Iterable<T> iterable) { 043 List<T> result = new ArrayList<T>(); 044 for (T element : iterable) { 045 result.add(element); 046 } 047 return result; 048 } 049 050 public static String mapToString(Map<?, ?> map) { 051 return map.keySet().stream() 052 .map(k -> k + "=" + map.get(k)) 053 .collect(Collectors.joining(",\n", "{\n", "\n}")); 054 } 055 056 /** 057 * Contract for {@link Collection}-s mapping. 058 * 059 * @param <T_Result> type of result 060 * @param <T_Source> type of source 061 */ 062 public interface Mapper<T_Result, T_Source> { 063 064 /** 065 * Maps a provided value. 066 * 067 * @param input for mapping 068 * @return mapped value 069 */ 070 T_Result map(T_Source input); 071 } 072}