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

28th Jul 2021, 2:34 PM
Roderick Davis
Roderick Davis - avatar
5 Respostas
+ 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.
28th Jul 2021, 3:05 PM
你知道規則,我也是
你知道規則,我也是 - avatar
+ 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
28th Jul 2021, 6:30 PM
Tibor Santa
Tibor Santa - avatar
+ 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 :)
28th Jul 2021, 6:41 PM
Tibor Santa
Tibor Santa - avatar
0
Thanks looking for a way to store each individual value from the arrays into the set.
28th Jul 2021, 3:12 PM
Roderick Davis
Roderick Davis - avatar
0
Tibor Santa stream seems like the only way im not very familiar with using them
28th Jul 2021, 6:36 PM
Roderick Davis
Roderick Davis - avatar