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