1

I have following statement creating an array of array of String:

String[][] strArr = {{"Jazz","80"},{"sam","90"},{"shaam","80"},{"aditya","100"}};

Would it be possible to get stream as following? I tried it in Eclipse but got an error.

Stream<String,String> streamObj = Arrays.stream(strArr);

Tried to search on net but mostly results were showing to get stream from 1-D array of strings as shown below:

String[] stringArr = {"a","b","c","d"};
Stream<String> str = Arrays.stream(stringArr);
1
  • 1
    Arrays.stream(strArr).flatMap(Arrays::stream) Commented Nov 11, 2019 at 15:39

2 Answers 2

2

There is no feasible representation such as Stream<String, String> with the java.util.stream.Stream class since the generic implementation for it relies on a single type such as it declared to be:

public interface Stream<T> ...

You might still collect the mapping in your sub-arrays as a key-value pair in a Map<String, String> as:

Map<String, String> map = Arrays.stream(strArr)
        .collect(Collectors.toMap(s -> s[0], s -> s[1]));

To wrap just the entries further without collecting them to a Map, you can create a Stream of SimpleEntry as :

Stream<AbstractMap.SimpleEntry<String, String>> entryStream = Arrays.stream(strArr)
        .map(sub -> new AbstractMap.SimpleEntry<>(sub[0], sub[1]));
Sign up to request clarification or add additional context in comments.

Comments

1

You can define a POJO called StringPair and map the stream.

public class PairStream {

    public static void main(String[] args) {
        String[][] strArr = {{"Jazz","80"},{"sam","90"},{"shaam","80"},{"aditya","100"}};
        Arrays.stream( strArr ).map( arr -> new StringPair(arr) ).forEach( pair -> System.out.println(pair) );
    }

    private static class StringPair {
        private final String first;
        private final String second;

        public StringPair(String[] array) {
            this.first = array[0];
            this.second = array[1];
        }
        @Override
        public String toString() {
            return "StringPair [first=" + first + ", second=" + second + "]";
        }
    }
}

As well as you can use Apache Commons lang Pair

public class PairStream {

    public static void main(String[] args) {
        String[][] strArr = {{"Jazz","80"},{"sam","90"},{"shaam","80"},{"aditya","100"}};
        Arrays.stream( strArr ).map( arr -> Pair.of(arr[0],arr[1]) ).forEach( pair -> System.out.println(pair) );
    }


}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.