Home » Collections
Archiv der Kategorie: Collections
Reihen generiern mit Stream-API
public class LerneUnendlicheReihen { public static void main(String[] args) { IntStream reihe = IntStream.iterate(100, i -> ++i); reihe.limit(100).forEach(System.out::println); /** * Output: * 100 * 101 * ...usw... * 199 */ "abcdefg".chars().forEach(System.out::println); System.out.println("Nun mit Integer Objekten:"); AtomicInteger atomicInteger = new AtomicInteger(100); Stream<Integer> objektReihe = Stream.generate(atomicInteger::getAndIncrement); objektReihe.limit(10).forEach(System.out::println); /* Ausgabe: Nun mit Integer Objekten: 100 101 * ...usw... 109 */ } }
Comparator – Schnelles Erstellen
Comparator personaComparator = Comparator.<strong>comparing</strong>(Persona::getAge).<strong>thenComparing</strong>(Persona::getName))
import static org.assertj.core.api.Assertions.assertThat; public class LerneComparator { final static Persona JONA = new Persona(7, "Jona"); final static Persona ZORA = new Persona(11, "Zora"); final static Persona NATASHA = new Persona(22, "Natasha"); final static Persona[] personas = {JONA, ZORA, NATASHA}; public static void main(String[] args) { List<Persona> personList = Arrays.asList(personas); System.out.println("Mit Comparator:"); Collections.sort(personList, Comparator.comparing(Persona::getAge).thenComparing(Persona::getName)); assertThat(personList).containsExactly(JONA, ZORA, NATASHA); System.out.println("Mit Comparator (reverse order):"); Collections.sort(personList, Comparator.comparing(Persona::getAge).thenComparing(Persona::getName).reversed()); assertThat(personList).containsExactly(NATASHA, ZORA, JONA); System.out.println("Mit Comparable Objects: "); Collections.sort(personList); //Persona must implement Comparable-Interface assertThat(personList).containsExactly(JONA, NATASHA, ZORA); } }
List mit einem einzigen Element erstellen
public static <T> List<T> singletonList(T o) { return new SingletonList<>(o); }
Hinzufuegen zu mapped Liste (:Map.computeIfAbsent)
Eine Liste innerhalb einer Map erweitern falls sie schon vorhanden ist oder sonst neu erstellen:
private Map<Object, List<Object>> addToMappedList1(Map<Object, List<Object>> mapOfLists, Object key, Object newValue){ if (mapOfLists.get(key) == null){ mapOfLists.put(key, new ArrayList<>()); } mapOfLists.get(key).add(newValue); return mapOfLists; }
Eleganter:
private Map<Object, List<Object>> addToMappedList2(Map<Object, List<Object>> mapOfLists, Object key, Object newValue){ mapOfLists.computeIfAbsent(key, k -> new ArrayList<>()).add(newValue); return mapOfLists; }