pho*_*nix 49 java string collections
我想将包含的字符串转换为字符abc列表和字符的哈希集.我怎么能用Java做到这一点?
List<Character> charList = new ArrayList<Character>("abc".toCharArray());
Run Code Online (Sandbox Code Playgroud)
wag*_*ans 44
在Java8中,您可以使用我想要的流.角色对象列表:
List<Character> chars = str.chars()
.mapToObj(e->(char)e).collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
并且可以以类似的方式获得set:
Set<Character> charsSet = str.chars()
.mapToObj(e->(char)e).collect(Collectors.toSet());
Run Code Online (Sandbox Code Playgroud)
Paŭ*_*ann 43
您将不得不使用循环,或创建一个类似于Arrays.asList原始字符数组(或直接在字符串上)的集合包装器.
List<Character> list = new ArrayList<Character>();
Set<Character> unique = new HashSet<Character>();
for(char c : "abc".toCharArray()) {
list.add(c);
unique.add(c);
}
Run Code Online (Sandbox Code Playgroud)
这是一个Arrays.asList类似于字符串的包装器:
public List<Character> asList(final String string) {
return new AbstractList<Character>() {
public int size() { return string.length(); }
public Character get(int index) { return string.charAt(index); }
};
}
Run Code Online (Sandbox Code Playgroud)
不过,这是一个不可变的列表.如果你想要一个可变列表,请使用以下命令char[]:
public List<Character> asList(final char[] string) {
return new AbstractList<Character>() {
public int size() { return string.length; }
public Character get(int index) { return string[index]; }
public Character set(int index, Character newVal) {
char old = string[index];
string[index] = newVal;
return old;
}
};
}
Run Code Online (Sandbox Code Playgroud)
与此类似,您可以为其他原始类型实现此功能. 请注意,建议不要使用此选项,因为对于每次访问,您都会执行装箱和拆箱操作.
所述番石榴库包含几个基本数组类相似列表包装方法,像Chars.asList,并在弦乐的包装Lists.charactersOf(字符串).
Mar*_*ers 31
某些第三方库解决了在原始数组和其相应包装类型集合之间转换的好方法.Guava是一种非常常见的方法,它有一种方便的方法来进行转换:
List<Character> characterList = Chars.asList("abc".toCharArray());
Set<Character> characterSet = new HashSet<Character>(characterList);
Run Code Online (Sandbox Code Playgroud)
Moi*_*ira 14
使用Java 8 Stream.
myString.chars().mapToObj(i -> (char) i).collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
分解:
myString
.chars() // Convert to an IntStream
.mapToObj(i -> (char) i) // Convert int to char, which gets boxed to Character
.collect(Collectors.toList()); // Collect in a List<Character>
Run Code Online (Sandbox Code Playgroud)
(我完全不知道为什么要String#chars()回来IntStream.)
最直接的方法是使用for循环向新的元素添加元素List:
String abc = "abc";
List<Character> charList = new ArrayList<Character>();
for (char c : abc.toCharArray()) {
charList.add(c);
}
Run Code Online (Sandbox Code Playgroud)
同样,对于Set:
String abc = "abc";
Set<Character> charSet = new HashSet<Character>();
for (char c : abc.toCharArray()) {
charSet.add(c);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
121470 次 |
| 最近记录: |