source: trunk/src/de/endrullis/utils/CollectionUtils.java @ 1116

Last change on this file since 1116 was 1116, checked in by stefan, 6 years ago

removed unnecessary import

File size: 2.4 KB
Line 
1package de.endrullis.utils;
2
3import util.Function1;
4
5import java.util.ArrayList;
6import java.util.Iterator;
7import java.util.List;
8
9/**
10 * Collection utils for Java.
11 *
12 * @author Stefan Endrullis <stefan@endrullis.de>
13 */
14public class CollectionUtils {
15  /**
16   * Concatenates the elements from the collection to one string.
17   * If the collection is empty an empty string is returned.
18   *
19   * @param collection collection
20   * @param delimiter  delimiter between the elements
21   * @return concatenation
22   */
23  public static String join(Iterable collection, String delimiter) {
24    return join(collection.iterator(), delimiter);
25  }
26
27  /**
28   * Concatenates the elements of the iterator to one string.
29   * If the iterator has no elements an empty string is returned.
30   *
31   * @param iterator  iterator
32   * @param delimiter delimiter between the elements
33   * @return concatenation
34   */
35  public static String join(Iterator iterator, String delimiter) {
36    return join(iterator, "", delimiter, "");
37  }
38
39  /**
40   * Concatenates the elements from the collection to one string.
41   * If the collection is empty an empty string is returned.
42   *
43   * @param collection collection
44   * @param start      start string
45   * @param delimiter  delimiter between the elements
46   * @param end        end string
47   * @return concatenation
48   */
49  public static String join(Iterable collection, String start, String delimiter, String end) {
50    return join(collection.iterator(), start, delimiter, end);
51  }
52
53  /**
54   * Concatenates the elements of the iterator to one string.
55   * If the iterator has no elements an empty string is returned.
56   *
57   * @param iterator  iterator
58   * @param start     start string
59   * @param delimiter delimiter between the elements
60   * @param end       end string
61   * @return concatenation
62   */
63  public static String join(Iterator iterator, String start, String delimiter, String end) {
64    if (iterator.hasNext()) {
65      StringBuffer s = new StringBuffer();
66
67      s.append(start);
68      s.append(iterator.next());
69
70      while (iterator.hasNext()) {
71        s.append(delimiter);
72        s.append(iterator.next());
73      }
74
75      s.append(end);
76
77      return s.toString();
78    } else {
79      return "";
80    }
81  }
82
83  public static <T,R> List<R> map(List<T> list, Function1<T,R> f) {
84    ArrayList<R> newList = new ArrayList<R>();
85    for (T t : list) {
86      newList.add(f.apply(t));
87    }
88    return newList;
89  }
90}
Note: See TracBrowser for help on using the repository browser.