0
Multidimensional array to hashset
Is there a way to initialize a hashset in Java with a 2d array? I prefer not to iterate through the array and add each one. https://code.sololearn.com/cbZGuXBcM0Gi/?ref=app
5 ответов
+ 2
Your set does store the arrays. set.contains(arr[0]) returns true.
However, set.contains(new int[]{1, 2}) returns false, so you need a workaround to find the array in the set.
+ 1
var set = Arrays.stream(arr)
.map(Arrays::stream)
.reduce(IntStream.empty(), IntStream::concat)
.mapToObj(Integer::new)
.collect(Collectors.toSet());
https://code.sololearn.com/crhl1R6w5yQK/?ref=app
+ 1
Roderick Davis you can also use two nested for loops and add each element to the hashset one by one, but I think streams are more elegant, although a bit difficult to master :)
0
Thanks looking for a way to store each individual value from the arrays into the set.
0
Tibor Santa stream seems like the only way im not very familiar with using them