在一次采访中,有人问我这个问题,老师给了我一个字符串,然后他们输入了他们教的相应学科的字符串。该任务以获取科目和相应的教师为输出。我已经解决了,但是我有几个问题:
这是我的程序的输入:
T1:S1,S3|T2:S1,S2,S4|T3:S1,S4,S5
这里T代表老师,S代表学生。在上面的示例中,老师T1教科目S1和S3。 T2老师教S1,S2,S4等科目
现在的要求是获取主题和相应的老师。
["S1:T1,T2,T3", "S2:T2", "S3:T1", "S4:T2,T3", "S5:T3"]
这意味着科目S1由老师T1,T2,T3教。 S2由T1等教。
我想出了以下正确运行的代码:
/**
* input: "T1:S1,S3|T2:S1,S2,S4|T3:S1,S4,S5"
* output : ["S1:T1,T2,T3", "S2:T2", "S3:T1", "S4:T2,T3", "S5:T3"]
*/
static List<String> process(String input) {
List<String> output = null;
// Split by |
String[] arr = input.split("\\|");
Map<String, List<String>> map = new HashMap<>();
// map with key as Teacher name and value as list of students
for(int i=0; i< arr.length; i++) {
String[] data = arr[i].split(":");
map.put(data[0], Arrays.asList(data[1].split(",")));
}
Map<String, List<String>> res = new TreeMap<>();
//Build map with key as student and value as list of teachers
for(String key : map.keySet()) {
List<String> list = map.get(key);
for(String val : list) {
List<String> temp = res.get(val);
if(temp == null) {
temp = new ArrayList<>();
res.put(val, temp);
}
temp.add(key);
}
}
output = new ArrayList<>();
// Build the output as per requirement
for(String key : res.keySet()) {
StringBuilder sb = new StringBuilder();
List<String> temp = res.get(key);
for(String v : temp)
{
sb.append(v).append(",");
}
output.add(key + ":" + sb.toString().substring(0, sb.toString().length()-1) );
}
return output;
}
您能帮我解决这些疑问吗?
答案 0 :(得分:1)
仅回答您要将其转换为Java 8 Stream API的部分,因此随时不要接受此回答:)
public static void main(String[] args) {
String input = "T1:S1,S3|T2:S1,S2,S4|T3:S1,S4,S5";
System.out.println(process(input));
}
private static List<String> process(String input) {
return Arrays.stream(input.split("\\|"))
.flatMap(s -> List.of(s.split(":")[1].split(","))
.stream()
.map(s1 -> s.split(":")[0] + ":" + s1))
.collect(Collectors.toMap(o -> o.split(":")[1],
o -> o.split(":")[0],
(o1, o2) -> o1 + "," + o2))
.entrySet().stream()
.map(e -> e.getKey() + ":" + e.getValue())
.collect(Collectors.toList());
}
输出
[S3:T1, S4:T2,T3, S5:T3, S1:T1,T2,T3, S2:T2]