문자열을 ArrayList로 변환하는 방법은 무엇입니까?
내 문자열에서 쉼표로 구분 된 임의의 수의 단어를 가질 수 있습니다. 각 단어를 ArrayList에 추가하고 싶었습니다. 예 :
String s = "a,b,c,d,e,.........";
다음과 같은 시도
List<String> myList = new ArrayList<String>(Arrays.asList(s.split(",")));
데모:
String s = "lorem,ipsum,dolor,sit,amet";
List<String> myList = new ArrayList<String>(Arrays.asList(s.split(",")));
System.out.println(myList); // prints [lorem, ipsum, dolor, sit, amet]
이 게시물은 여기 에 기사로 다시 작성되었습니다 .
String s1="[a,b,c,d]";
String replace = s1.replace("[","");
System.out.println(replace);
String replace1 = replace.replace("]","");
System.out.println(replace1);
List<String> myList = new ArrayList<String>(Arrays.asList(replace1.split(",")));
System.out.println(myList.toString());
Java 9에서는 List#of
Immutable List Static Factory Methods 인를 사용 하는 것이 더 간단 해졌습니다.
String s = "a,b,c,d,e,.........";
List<String> lst = List.of(s.split(","));
옵션 1 :
List<String> list = Arrays.asList("hello");
옵션 2 :
List<String> list = new ArrayList<String>(Arrays.asList("hello"));
제 생각에는 Option1이 더 좋습니다.
- 생성되는 ArrayList 객체의 수를 2 개에서 1 개로 줄일 수 있습니다.
asList
메소드는 ArrayList 객체를 생성하고 반환합니다. - 성능이 훨씬 더 좋습니다 (그러나 고정 크기 목록을 반환합니다).
가져 오는 중이거나 코드에 배열 (문자열 유형)이 있고이를 arraylist (오프 코스 문자열)로 변환해야하는 경우 컬렉션을 사용하는 것이 좋습니다. 이렇게 :
String array1[] = getIntent().getExtras().getStringArray("key1"); or String array1[] = ... then
List allEds = new ArrayList(); Collections.addAll(allEds, array1);
문자열 을 ArrayList 로 변환하려면 다음을 시도하십시오.
public ArrayList<Character> convertStringToArraylist(String str) {
ArrayList<Character> charList = new ArrayList<Character>();
for(int i = 0; i<str.length();i++){
charList.add(str.charAt(i));
}
return charList;
}
하지만 귀하의 예제에서 문자열 배열을 볼 수 있으므로 문자열 배열 을 ArrayList 로 변환 하려면 다음을 사용하십시오.
public static ArrayList<String> convertStringArrayToArraylist(String[] strArr){
ArrayList<String> stringList = new ArrayList<String>();
for (String s : strArr) {
stringList.add(s);
}
return stringList;
}
Ok 여기에 오는 많은 사람들이 문자열을 공백 으로 나누기를 원하기 때문에 여기에 대한 답변을 확장하겠습니다 . 이것이 수행되는 방법입니다.
List<String> List = new ArrayList<String>(Arrays.asList(s.split("\\s+")));
다음을 사용할 수 있습니다.
List<String> tokens = Arrays.stream(s.split("\\s+")).collect(Collectors.toList());
You should ask yourself if you really need the ArrayList in the first place. Very often, you're going to filter the list based on additional criteria, for which a Stream is perfect. You may want a set; you may want to filter them by means of another regular expression, etc. Java 8 provides this very useful extension, by the way, which will work on any CharSequence
: https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html#splitAsStream-java.lang.CharSequence-. Since you don't need the array at all, avoid creating it thus:
// This will presumably be a static final field somewhere.
Pattern splitter = Pattern.compile("\\s+");
// ...
String untokenized = reader.readLine();
Stream<String> tokens = splitter.splitAsStream(untokenized);
Easier to understand is like this:
String s = "a,b,c,d,e";
String[] sArr = s.split(",");
List<String> sList = Arrays.asList(sArr);
Let's take a question : Reverse a String. I shall do this using stream().collect(). But first I shall change the string into an ArrayList .
public class StringReverse1 {
public static void main(String[] args) {
String a = "Gini Gina Proti";
List<String> list = new ArrayList<String>(Arrays.asList(a.split("")));
list.stream()
.collect(Collectors.toCollection( LinkedList :: new ))
.descendingIterator()
.forEachRemaining(System.out::println);
}}
/*
The output :
i
t
o
r
P
a
n
i
G
i
n
i
G
*/
I recommend use the StringTokenizer, is very efficient
List<String> list = new ArrayList<>();
StringTokenizer token = new StringTokenizer(value, LIST_SEPARATOR);
while (token.hasMoreTokens()) {
list.add(token.nextToken());
}
This is using Gson in Kotlin
val listString = "[uno,dos,tres,cuatro,cinco]"
val gson = Gson()
val lista = gson.fromJson(listString , Array<String>::class.java).toList()
Log.e("GSON", lista[0])
If you're using guava (and you should be, see effective java item #15):
ImmutableList<String> list = ImmutableList.copyOf(s.split(","));
This is the answer recommended by Android
<string-array name="android_versions">
<item>Android</item>
<item>Ice Cream Sandwich</item>
<item>Jelly Bean</item>
<item>Kitkat</item>
<item>Lollipop</item>
<item>Marshmallow</item>
<item>Nougat</item>
<item>Oreo</item>
<item>Pie</item>
<item>Q</item>
</string-array>
ArrayList<String> names = new ArrayList<>();
//List<String> names = new ArrayList<>();
Collections.addAll(names, getResources().getStringArray(R.array.android_versions));
참고URL : https://stackoverflow.com/questions/7347856/how-to-convert-a-string-into-an-arraylist
'code' 카테고리의 다른 글
Ajax 처리의 "잘못된 JSON 기본 요소" (0) | 2020.09.02 |
---|---|
Node 및 Express 4를 사용한 기본 HTTP 인증 (0) | 2020.09.02 |
위치로 HashMap에서 요소를 가져올 수 있습니까? (0) | 2020.09.02 |
PostgreSQL에서 중복 레코드 삭제 (0) | 2020.09.02 |
부트 스트랩 선택 드롭 다운 목록 자리 표시 자 (0) | 2020.09.02 |