简体   繁体   English

如何从字符串数组中获取 Stream?

[英]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?是否有可能得到 stream 如下? I tried it in Eclipse but got an error.我在 Eclipse 中尝试过,但出现错误。

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:尝试在网上搜索,但大多数结果显示从一维字符串数组中获取 stream,如下所示:

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: 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>中的键值对collect为:

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:要进一步包装条目而不将它们收集到Map ,您可以创建StreamSimpleEntry为:

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.您可以定义一个名为 StringPair 的 POJO 和 map 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以及您可以使用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) );
    }


}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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