Java Stream API, Collect result into Map<code, concatenated string> from a List containing two separate lists

huangapple go评论89阅读模式
英文:

Java Stream API, Collect result into Map<code, concatenated string> from a List containing two separate lists

问题

以下是使用Java 8 Stream API 改进的代码,它会生成所需的输出:

Map<Integer, String> map = subgroups.stream()
    .flatMap(subgroup -> subgroup.getNames().stream()
        .filter(name -> getMatching(subgroup, name))
        .map(name -> Map.entry(name.getLanguageCode(), name.getLongName() + "~" + getLevelLongName(subgroup, name)))
    )
    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

public static boolean getMatching(Subgroup sg, Name name) {
    return sg.getLevel().getNames().stream()
            .anyMatch(ln -> ln.getLanguages() == name.getLanguageCode());
}

private static String getLevelLongName(Subgroup subgroup, Name name) {
    return subgroup.getLevel().getNames().stream()
            .filter(levelName -> levelName.getLanguages() == name.getLanguageCode())
            .map(Names::getLongName)
            .findFirst()
            .orElse("");
}

这段代码会使用Stream API 处理输入列表,并生成一个以语言代码为键,以连接的名称为值的映射。

英文:

Here is the code which need to generate the output as follows using Stream API.

Input:

[Subgroup(id=1, names=[Name(languageCode=1, longName=ABD), Name(languageCode=2, longName=BD)], level=Level(names=[Names(languages=1, longName=1 1), Names(languages=2, longName=2 2)]))]

Output:

Map:{1=ABD~1 1, 2=BD~2 2}

Java-6: Code which generates the required output. but, we need to use Stream API and collect the output because the Sample input i am providing only single obj. Where in realtime i am having more than 50 objects. So, i need it in Advanced version of Java.

public class SubgroupProcessor {
	public static void main(String[] args) {
		List&lt;Name&gt; names = Arrays.asList(new Name(1, &quot;ABD&quot;), new Name(2, &quot;BD&quot;));
		List&lt;Names&gt; namesLevel = Arrays.asList(new Names(1, &quot;1 1&quot;), new Names(2, &quot;2 2&quot;));
		List&lt;Subgroup&gt; subgroups = Arrays.asList(new Subgroup(1, names, new Level(namesLevel)));
		System.out.println(subgroups);

		Map&lt;Integer, String&gt; map = new HashMap&lt;&gt;();
		for (Subgroup subgroup : subgroups) {
			List&lt;Name&gt; names2 = subgroup.getNames();
			List&lt;Names&gt; namesLevel2 = subgroup.getLevel().getNames();
			for (Name name : names2) {
				for (Names nameLevel : namesLevel2) {
					if (nameLevel.getLanguages() == name.getLanguageCode()) {
						map.put(name.getLanguageCode(), name.getLongName() + &quot;~&quot; + nameLevel.getLongName());
					}
				}
			}
		}
		System.out.println(&quot;Map:&quot;+map);
	}
}

@Data @AllArgsConstructor
class Subgroup {
	private int id;
	private List&lt;Name&gt; names;
	private Level level;
}

@Data @AllArgsConstructor
class Name {
	private int languageCode;
	private String longName;
}

@Data @AllArgsConstructor
class Names {
	private int languages;
	private String longName;
}

@Data @AllArgsConstructor
class Level {
	private List&lt;Names&gt; names;
}

Tried Chat-GPT as well but generated the following code and its not working.

This code uses Java 8 streams to process the input list and produce the required output in the form of a map with language codes as keys and concatenated names as values.

Map&lt;Integer, String&gt; map = subgroups.stream()
	.flatMap(subgroup -&gt; subgroup.getNames().stream()
			.filter(name -&gt; getMatching(subgroup, name))
			.map(name -&gt; Map.entry(name.getLanguageCode(), name.getLongName() + &quot;~&quot; + getLevelLongName(subgroup, name)))
	)
	.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    

public static boolean getMatching(Subgroup sg, Name name) {
	return sg.getLevel().getNames().stream()
			.anyMatch(ln -&gt; ln.getLanguages() == name.getLanguageCode());
}

private static String getLevelLongName(Subgroup subgroup, Name name) {
	return subgroup.getLevel().getNames().stream()
			.filter(levelName -&gt; levelName.getLanguages() == name.getLanguageCode())
			.map(Names::getLongName)
			.findFirst()
			.orElse(&quot;&quot;);
}

答案1

得分: 0

以下是您要的翻译:

你可以尝试类似这样的代码
Map<Integer, String> result = subgroups.stream()
        .flatMap(subgroup -> 
            subgroup.getNames().stream()
                .map(name -> new AbstractMap.SimpleEntry<>(
                    name.getLanguageCode(), 
                    name.getLongName() + "~" + 
                        subgroup.getLevel().getNames().stream()
                            .filter(levelName -> levelName.getLanguages() == name.getLanguageCode())
                            .map(Names::getLongName)
                            .findFirst()
                            .orElse("")))
        )
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
英文:

You may try something like this instead:

Map&lt;Integer, String&gt; result = subgroups.stream()
.flatMap(subgroup -&gt; 
subgroup.getNames().stream()
.map(name -&gt; new AbstractMap.SimpleEntry&lt;&gt;(
name.getLanguageCode(), 
name.getLongName() + &quot;~&quot; + 
subgroup.getLevel().getNames().stream()
.filter(levelName -&gt; levelName.getLanguages() == name.getLanguageCode())
.map(Names::getLongName)
.findFirst()
.orElse(&quot;&quot;)))
)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

huangapple
  • 本文由 发表于 2023年8月5日 02:27:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76838386.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定