简体   繁体   中英

How to get Stream from an array of array of String?

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);

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]));

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) );
    }


}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM