Home Ask Login Register

Developers Planet

Your answer is one click away!

Terry Ruas February 2016

Grouping values by a common attribute in a matrix

I'm having trouble in transforming a 2-D Matrix into an 2D Array/List/Vector based on a common value of the original Matrix.

For example I have an ordered 2d_array of String(the code is quite big) as shown bellow.

String [][] 2d_array  =  { {1922, ABC}, {1922, XPT}, {1954,ABC}, {2001, SSS}, {2001, asd}}; // this array has "N" row

I would like to transform/create the following "output".

new_array = {{1922, ABC, XPT}, {1954, ABC}, {2001, SSS, asd}};

In this new array does not matter how long the number of columns will be, as long as they are all in the same row with the accordingly "number"/date/index/etc.

Answers


Jean Logeart February 2016

Try:

Map<String, Set<String>> res = 
  Arrays.stream(2d_array)
        .collect(groupingBy(a -> a[0], mapping(a -> a[1], toSet())));

You can convert this map to the desired array if you find the array more convenient.

Post Status

Asked in February 2016
Viewed 3,836 times
Voted 7
Answered 1 times

Search




Leave an answer


Quote of the day: live life