목록 변환 목록에 직접
내 파일 "s"를 구문 분석 한 후 AttributeGet:1,16,10106,10111
따라서 attributeIDGet 목록에서 콜론 뒤의 모든 숫자를 가져와야합니다. 몇 가지 방법이 있다는 것을 알고 있습니다. 그러나 우리가 할 수있는 모든 방법은 직접 변환 List<String>
에가 List<Integer>
. 아래 코드는 유형 불일치에 대해 불평하므로 Integer.parseInt를 시도했지만 List에서는 작동하지 않을 것 같습니다. 여기는 String입니다.
private static List<Integer> attributeIDGet = new ArrayList<Integer>();
if(s.contains("AttributeGet:")) {
attributeIDGet = Arrays.asList(s.split(":")[1].split(","));
}
아니요, 배열을 반복해야합니다.
for(String s : strList) intList.add(Integer.valueOf(s));
Java8 사용 :
stringList.stream().map(Integer::parseInt).collect(Collectors.toList());
람다 사용 :
strList.stream().map(org.apache.commons.lang3.math.NumberUtils::toInt).collect(Collectors.toList());
Guava 변환기 가 트릭을 수행합니다.
import com.google.common.base.Splitter;
import com.google.common.primitives.Longs;
final Iterable<Long> longIds =
Longs.stringConverter().convertAll(
Splitter.on(',').trimResults().omitEmptyStrings()
.splitToList("1,2,3"));
아니요, 각 요소를 반복해야합니다.
for(String number : numbers) {
numberList.add(Integer.parseInt(number));
}
이런 일이 발생하는 이유는에 한 종류의 목록을 변환 할 간단한 방법이 없다는 것입니다 다른 유형입니다. 일부 변환은 불가능하거나 특정 방식으로 수행해야합니다. 본질적으로 변환은 관련된 개체와 변환의 컨텍스트에 따라 달라 지므로 "하나의 크기에 모두 적용되는"솔루션은 없습니다. 예를 들어, Car
물건과 물건 이 있다면 Person
어떨까요? 실제로 의미가 없기 때문에 a List<Car>
를로 List<Person>
직접 변환 할 수 없습니다 .
Google Guava 라이브러리 를 사용하는 경우이 작업을 수행 할 수 있습니다. Lists # transform을 참조하세요 .
String s = "AttributeGet:1,16,10106,10111";
List<Integer> attributeIDGet = new ArrayList<Integer>();
if(s.contains("AttributeGet:")) {
List<String> attributeIDGetS = Arrays.asList(s.split(":")[1].split(","));
attributeIDGet =
Lists.transform(attributeIDGetS, new Function<String, Integer>() {
public Integer apply(String e) {
return Integer.parseInt(e);
};
});
}
네, 위의 답변에 동의합니다. 그러나 그것은 다른 방법 일뿐입니다.
스트림을 사용하여 문자열 목록을 정수 목록으로 변환하지 않는 이유는 무엇입니까? 아래와 같이
List<String> stringList = new ArrayList<String>(Arrays.asList("10", "30", "40",
"50", "60", "70"));
List<Integer> integerList = stringList.stream()
.map(Integer::valueOf).collect(Collectors.toList());
완전한 작업은 다음과 같을 수 있습니다.
String s = "AttributeGet:1,16,10106,10111";
List<Integer> integerList = (s.startsWith("AttributeGet:")) ?
Arrays.asList(s.replace("AttributeGet:", "").split(","))
.stream().map(Integer::valueOf).collect(Collectors.toList())
: new ArrayList<Integer>();
Java 8의 람다를 사용할 수있는 경우 다음 코드 샘플을 사용할 수 있습니다.
final String text = "1:2:3:4:5";
final List<Integer> list = Arrays.asList(text.split(":")).stream()
.map(s -> Integer.parseInt(s))
.collect(Collectors.toList());
System.out.println(list);
외부 라이브러리를 사용하지 않습니다. 평범한 오래된 새로운 자바!
Java 8의 Lambda 함수를 사용하여 루프없이이를 수행 할 수 있습니다.
String string = "1, 2, 3, 4";
List<Integer> list = Arrays.asList(string.split(",")).stream().map(s -> Integer.parseInt(s.trim())).collect(Collectors.toList());
아니요, Java에서 수행 할 수있는 방법은 없습니다 (내가 알고있는).
기본적으로 각 항목을 문자열에서 정수로 변환해야합니다.
원하는 것은보다 기능적인 언어로 달성 할 수 있습니다. 여기서 변형 함수를 전달하고 목록의 모든 요소에 적용 할 수 있습니다 ...하지만 가능하지 않습니다 (목록의 모든 요소에 여전히 적용됩니다). ).
지나침:
You can, however use a Function from Google Guava (http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Function.html) to simulate a more functional approach, if that is what you're looking for.
If you're worried about iterating over the list twice, then instead of split use a Tokenizer and transform each integer token to Integer before adding to the list.
Here is another example to show power of Guava. Although, this is not the way I write code, I wanted to pack it all together to show what kind of functional programming Guava provides for Java.
Function<String, Integer> strToInt=new Function<String, Integer>() {
public Integer apply(String e) {
return Integer.parseInt(e);
}
};
String s = "AttributeGet:1,16,10106,10111";
List<Integer> attributeIDGet =(s.contains("AttributeGet:"))?
FluentIterable
.from(Iterables.skip(Splitter.on(CharMatcher.anyOf(";,")).split(s)), 1))
.transform(strToInt)
.toImmutableList():
new ArrayList<Integer>();
You can consider code in my repo.
https://github.com/mohamedanees6/JavaUtils/wiki/CollectionUtils
castStringCollection(Collection<T>,Class)
Using Streams and Lambda:
newIntegerlist = listName.stream().map(x->
Integer.valueOf(x)).collect(Collectors.toList());
The above line of code will convert the List of type List<String>
to List<Integer>
.
I hope it was helpful.
ReferenceURL : https://stackoverflow.com/questions/10706721/convert-liststring-to-listinteger-directly
'programing' 카테고리의 다른 글
입력에 '읽기 전용'속성이있는 경우 감지 (0) | 2021.01.16 |
---|---|
Android에서 Wi-Fi 활성화 여부 확인 (0) | 2021.01.16 |
Sass :: SyntaxError : 가져올 파일을 찾을 수 없거나 읽을 수 없음 : bootstrap-sprockets (0) | 2021.01.16 |
Charts.js는 통화와 천 단위 구분자로 Y 축 서식 지정 (0) | 2021.01.16 |
Xcode 7에서 프로젝트 및 cocoapods 종속성에 대한 비트 코드를 비활성화 하시겠습니까? (0) | 2021.01.16 |