gpt4 book ai didi

java - 确定 String 的最长、最长和最长的 ArrayList

转载 作者:行者123 更新时间:2023-12-01 19:46:28 25 4
gpt4 key购买 nike

我有三 (3) 个不同大小的 ArrayList,我想知道哪个是长的、更长的和最长的。我想出了这个解决方案,效果很好,但看起来还不够优化。我希望有人为我优化它。提前致谢。

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class LongLongerLongest {


public static void main(String[] args){

/**
* Generated ArrayLists for testing
*/
List<String> first = Arrays.asList("qw", "sd", "asw");
List<String> second = Arrays.asList("qw", "sd", "r4", "asw",
"qw", "sd", "r4", "asw", "r4", "asw");
List<String> third = Arrays.asList("qw", "sd", "r4", "asw",
"r4", "asw", "oiu");


String result = sortLists(first,second, third);
System.out.println(result);
}



static String sortLists(List<String> firstList, List<String>
secondList, List<String> thirdList) {

/**
* declare a list to hold all sizes
*/
List<Integer> listOfSizes = new ArrayList<>();

List<String> longList;
List<String> longerList;
List<String> longestList;

/**
* Add the size of all array to the listOfSizes list and sort
*/
listOfSizes.add(firstList.size());
listOfSizes.add(secondList.size());
listOfSizes.add(thirdList.size());
Collections.sort(listOfSizes);

/**
* Searching for the longest
*/
if (firstList.size() == listOfSizes.get(2)) {
longestList = firstList;
}
else if (secondList.size() == listOfSizes.get(2)) {
longestList = secondList;
} else {
longestList = thirdList;
}

/**
* Searching for the longer
*/
if (firstList.size() == listOfSizes.get(1)) {
longerList = firstList;
}
else if (secondList.size() == listOfSizes.get(1)) {
longerList = secondList;
} else {
longerList = thirdList;
}

/**
* Searching for the long
*/
if (firstList.size() == listOfSizes.get(0)) {
longList = firstList;
}
else if (secondList.size() == listOfSizes.get(0)) {
longList = secondList;
} else {
longList = thirdList;
}

String result = "long: " + longList.toString() + ", longer: " +
longerList.toString() + ", longest: " + longestList.toString();
return result;
}

}

我上面的内容是为了找到三者的交集。但对于错误处理,我决定从最大的向下排序以避免空列表。

最佳答案

以下是减少代码量的 Stream API 方法:

static String sortLists(List<String> firstList, List<String> secondList, List<String> thirdList) {
return Stream.of(firstList, secondList, thirdList)
.sorted(Comparator.comparingInt(List::size))
.collect(collectingAndThen(toList(), f -> "long: " + f.get(0) + ", longer: " +
f.get(1) + ", longest: " + f.get(2)));
}

从三个列表创建一个流,然后按其大小排序,最后应用整理函数以获得预期的格式。

需要导入:

import static java.util.stream.Collectors.*;
import java.util.stream.*;

关于java - 确定 String 的最长、最长和最长的 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53093245/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com