How can I convert List to int[] in Java? [duplicate]

With streams added in Java 8 we can write code like: int[] example1 = list.stream().mapToInt(i->i).toArray(); // OR int[] example2 = list.stream().mapToInt(Integer::intValue).toArray(); Thought process: The simple Stream#toArray returns an Object[] array, so it is not what we want. Also, Stream#toArray(IntFunction<A[]> generator) doesn’t do what we want, because the generic type A can’t represent the primitive type … Read more

How to filter a Java Collection (based on predicate)?

Java 8 (2014) solves this problem using streams and lambdas in one line of code: List<Person> beerDrinkers = persons.stream() .filter(p -> p.getAge() > 16).collect(Collectors.toList()); Here’s a tutorial. Use Collection#removeIf to modify the collection in place. (Notice: In this case, the predicate will remove objects who satisfy the predicate): persons.removeIf(p -> p.getAge() <= 16); lambdaj allows … Read more

How to convert an Array to a Set in Java

Like this: Set<T> mySet = new HashSet<>(Arrays.asList(someArray)); In Java 9+, if unmodifiable set is ok: Set<T> mySet = Set.of(someArray); In Java 10+, the generic type parameter can be inferred from the arrays component type: var mySet = Set.of(someArray); Be careful Set.of throws IllegalArgumentException – if there are any duplicate elements in someArray. See more details: … Read more

How to initialize HashSet values by construction?

There is a shorthand that I use that is not very time efficient, but fits on a single line: Set<String> h = new HashSet<>(Arrays.asList(“a”, “b”)); Again, this is not time efficient since you are constructing an array, converting to a list and using that list to create a set. When initializing static final sets I … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)