So I am currently having a problem understanding how to access a set, is that even allowed? So I understand my set of names contains a set of Character objects. I also understand that my toString() method call converts these Character objects into a String, but not a conventional string -- which is why I have [s,a] rather than [sa]. So my question is, is if there is a way to make me have a list of individual strings. So I want my list to be = [s, a] rather than [ [s,a] ]. Is this even possible? I apologize if this makes no sense; nevertheless, if you do understand my fumbled explanation thank you for your time and help. If you need for me to explain more, I will.
//this all works
Set<Character> names = find(prefix).getRollCall().keySet();
//[s,a]
String lists = names.toString();
//[s,a]
List<String> sloop = Arrays.asList(lists);
//[[s,a]]
If you want to convert a Set<Character> to a List<Character> you can do
List<Character> list = new ArrayList<Character>(set);
If you want to convert a Set<Character> to a List<String> you can do
List<String> list = new ArrayList<String>();
for (char c : set)
list.add("" + c);
Don't use toString() at all. Iterate over the elements of the Set and build up whatever string you like.
Set<Character> names = find(prefix).getRollCall().keySet();
for (Character c : names)
{
// whatever you like
}
Let me explain what's happening in your code, in case you aren't clear:
String lists = names.toString();
This calls the standard toString method for a collection which converts your set to an ordinary (conventional) string in a standard format (i.e. comma delimited, in brackets). There's nothing special about the string that is created: "[s, a]".
List<String> sloop = Arrays.asList(lists);
The asList method takes one or more arguments and converts them into a list. Because you've given it only a single argument lists it creates a list with a single string element: ("[s, a]")
Then, later, I suspect you are doing something like:
System.out.println(sloop);
This again calls the standard toString method for a collection (in this case the List sloop) and again creates a comma delimited, bracket enclosed standard string: "[[s, a]]"
So, most of that is probably not what you want. Your lists variable isn't a List, it's a String which I assume isn't what you want.
If you are just looking to convert your set of character to a list of strings, then this is pretty trivial in Java 8:
List<String> lists = names.stream().map(Character::toString).collect(Collectors.toList());
Related
Hello I would like to make a custom method for ArrayList class.
So lets say I make a new ArrayList.
ArrayList<String> list = new ArrayList<String>
I would like to make a method I can call on list.
Something like this:
list.myMethod();
What I want to solve with my method is so you can get an Object by Object name and not index inside the ArrayList.
So basically I want to make a method returning following:
list.get(list.indexOf(str));
To sum it up:
ArrayList<String> list= new ArrayList<>();
String str = "asd";
String str2 = "zxc";
list.add(str2);
list.add(str);
System.out.println(list.get(0));
System.out.println(list.get(list.indexOf(str)));
Will print: "asd" "asd".
So instead of writing: list.get(list.indexOf(Object))
I would like to be a able to write list.myMethod(Object) and get the same result. I hope you understand my question. I know this is probably a dumb solution and I could just use a Map. But this is for learning purpose only and nothing I will use.
Custom method >>
public class MyArrayList<E> extends ArrayList<E> {
public E getLastItem(){
return get(size()-1);
}
}
How to use it >>
MyArrayList<String> list= new MyArrayList<>();
String str = "asd";
String str2 = "zxc";
list.add(str2);
list.add(str);
System.out.println(list.getLastItem());
what you need requires to extend the ArrayList classs, but you should consider using instead a
Map<String, Object>
with that approach you can do something like
myMap.get("myObject1");
You should just extend the ArrayList class creating your own with the new method. But the performance would be horrible if your list grow too much. The indexOf method have O(n), so greater is the size of your array longer is the time you have to wait.
May be you should choose a different collection if you want access directly to the element. In your case, it elements stored in the collection are unique, you could use a Set.
On the other hand, a Set does not preserve the insertion order. I don't know if this is a think you have to care of.
And a Set just let you know if the element is contained into the collection.
Another collection that can be of your interest is the Map, this is a key-value collection.
But given that you have only keys this it seems not be your case.
Maybe this is very simple but I'm actually a noob on Java 8 features and don't know how to accomplish this. I have this simple line that contains the following text:
"Key, Name"
and I want to convert that line into a String array, separating each value by the comma (,), however, I also want to trim every field before returning the final array, so I did the following:
Arrays.stream(line.split(",")).map(String::trim).toArray();
However, this returns an Object[] array rather than a String[] array. Upon further inspection, I can confirm that the contents are actually String instances, but the array itself is of Object elements. Let me illustrate this, this is what the debugger says of the returned object:
Object[]:
0 = (String) "Key"
1 = (String) "Name"
As far as I can tell, the problem is in the return type of the map call, but how can I make it return a String[] array?
Use toArray(size -> new String[size]) or toArray(String[]::new).
String[] strings = Arrays.stream(line.split(",")).map(String::trim).toArray(String[]::new);
This is actually a lambda expression for
.toArray(new IntFunction<String[]>() {
#Override
public String[] apply(int size) {
return new String[size];
}
});
Where you are telling convert the array to a String array of same size.
From the docs
The generator function takes an integer, which is the size of the desired array, and produces an array of the desired size. This can be concisely expressed with an array constructor reference:
Person[] men = people.stream()
.filter(p -> p.getGender() == MALE)
.toArray(Person[]::new);
Type Parameters:
A - the element type of the resulting array
Parameters:
generator - a function which produces a new array of the desired type and the provided length
String[]::new is a function that invokes the new "pseudo-method" for the String[] type just like String::trim is a function that invokes the real trim method of the String type. The value passed to the String::new function by toArray is the size of the collection on the right-hand side of the .toArray() method invocation.
If you replaced String[]::new with n->new String[n] you might be more comfortable with the syntax just like you could replace String::trim with the less cool s->s.trim()
I'm having a config entry, from which I'm loading into an String array like
String s = "abc$#def$#ghi";
String[] scbHLNewArray = s.split("\\$\\#");
Here I'm comparing a string with the array values after splitting it like ,
for(String arrNewErrorInfo : scbHLNewArray) {
LOG.info("SCB HL New Error Value :"+arrNewErrorInfo+"\n");
if(errorInfo.equals(arrNewErrorInfo)) {
LOG.info("SCB HL Matched New value is :"+arrNewErrorInfo);
newState = ApplicationState.NEW;
addApplicationEvent(application.getId(),comment, ApplicationEventType.COMMENT,BBConstants.AUTOBOT);
scbHLNewStatus = "Matched";
break;
}
}
I want to use some util classes like List.. Any idea on append to list and compare the string with the list objecT?
Thanks,
Nizam
you can do this with List contains method.
ArrayList<Integer> arrlist = new ArrayList<Integer<(8);
// use add() method to add elements in the list
arrlist.add(20);
arrlist.add(25);
arrlist.add(10);
arrlist.add(15);
// list contains element 10
boolean retval = arrlist.contains(10); // It will return true.
Ok, let's try... First of all, you can create a List Object, wrapping your array very easily:
List<String> myList = Arrays.asList( scbHLNewArray );
Be carefull, because you can NOT add to this list, as it only wraps your array. If you want a list you can add to, you would have to create a new one, for example:
List<String> myModifiableList = new ArrayList<String>( myList );
This will create a new List that contains all the Strings from the first one but is also modifiable (you can add Strings, if you want).
In any case, you can use "contains", as Pratik has already shown, to test if a String is inside your list:
if (myList.contains("someString")) { ... }
This works because the String class already has well implemented equals(...) and hashCode() methods. If you want to put other Object than Strings into your list, you would have to make sure that these methods are implemented well, otherwise contains might not work as expected.
Yes you can use a list of course, you need to :
1. Take the result of split as an array.
2. Then convert this array to a list.
String s = "abc$#def$#ghi";
String[] scbHLNewArray = s.split("\\$\\#");
List<String> list=Arrays.asList(scbHLNewArray); //convert the array to a list
Take a look at Arrays.asList(Array a) and this Tutorial for further information about it.
And then to search the wanted String object you can use indexOf(Object o) or contains(Object o) List methods
ok. Rookie question.
I have a scanned string that i would like to sort using Collections.sort(string).
The string comes from a scanned file that has a bunch of "asdfasdfasdf" in it.
I have scanned the file (.txt) and the scannermethod returns a String called scannedBok;
The string is then added to an ArrayList called skapaArrayBok();
here is the code:
public ArrayList<String> skapaArrayBok() {
ArrayList<String> strengar = new ArrayList<String>();
strengar.add(scanner());
Collections.sort(strengar);
return (strengar);
}
in my humble rookie brain the output would be "aaadddfffsss" but no.
This is a schoolasigment and the whole purpose of the project is to find the 10 most frequent words in a book. But i can't get it to sort. But i just would like to know why it won't sort the scanned string?
You are sorting the list, not the String. The list has only one element, so sorting it doesn't change anything.
In order to sort the content of the String, convert it to an array of characters, and sort the array.
Collections.sort() sorts the items in a list.
You have exactly one item in your list: the string "aaadddfffsss". There's nothing to sort.
SUGGESTIONS:
1) Read more strings into your collection
public ArrayList<String> skapaArrayBok() {
ArrayList<String> strengar = new ArrayList<String>();
// Input three strings
strengar.add(scanner());
strengar.add(scanner());
strengar.add(scanner());
// Now sort
Collections.sort(strengar);
... or ...
2) Split the string into characters, and sort the characters.
public ArrayList<String> skapaArrayBok() {
// Get string
String s = scanner());
char[] charArray = s.toCharArray();
Arrays.sort(charArray );
// Return sorted string
return (new String(charArray);
It is correct to sort "strengar", the ArrayList. However, it would not change the ordering of the ArrayList if you've only added one String to it. A list with one element is already sorted. If you want to sort the ArrayList, you should call add() on the ArrayList with each String you need to add, then sort.
You want to sort the characters within the String which is completely different and you need to re-organize the characters, a possible solution (especially knowing that Strings are immutable) is the following Sort a single String in Java
(No networking knowledge required whatsoever. This is purely String and Lists).
Say I have a function in place, one that accepts a list of String IPv4 dotted address, and sorts them in ascending order. (Not alphabetical, true ip long format sorting). Let's call this:
public static ArrayList<String> sortListOfIpv4s(ArrayList<String> unsortedIPv4s);
This function already works correctly. Given an input:
192.168.1.1, 8.8.8.8, 4.5.6.7, 244.244.244.244, 146.144.111.6
It will output the list:
4.5.6.7, 8.8.8.8, 146.144.111.6, 192.168.1.1, 244.244.244.244
(Let's not get into a debate on whether it should modify the list in place or return a new list. It just returns a new list. Also, the function cannot be modified because of numerous reasons.)
However, my input list looks like this:
e192.168.1.1, f8.8.8.8, e4.5.6.7, f244.244.244.244, e146.144.111.6
When I remove the prefixes (only one of e or f, NOT NECESSARILY alternating) and create a clean array to pass to the sorting function, I lose the prefix information. What I would like is an output of the type:
e4.5.6.7, f8.8.8.8, e146.144.111.6, e192.168.1.1, f244.244.244.244
Basically, prior to sorting, whatever prefix was present for each element in the unsorted list, the same prefix needs to be added back to the elements in the sorted list.
Caveats:
An IP Address can repeat in the original list, a maximum of two times
When repeating twice, each of the two elements will have the same prefix, guaranteed
Sorting algorithm will not remove duplicates.
A little algorithmic help please? (Remember, we already have a function that can sort clean IPv4 String arraylists).
Don't remove the prefixes prior to passing it to the sorting function. Instead, in the sortListOfIpv4s method, always compare Strings using s.substring(1), which will give you the entire string without the prefix, and add s to the resulting sorted array.
If sortListOfIpv4s is a black box and you are required to pass the prefix-free Strings, then you could cache the prefixes beforehand in a Map from prefix-free IP -> prefix:
Map<String, String> prefixMap = new HashMap<String, String>();
for (String ip : unsortedIPv4s) {
prefixMap.put(ip.substring(1), ip.substring(0, 1));
}
Then sort and recover the prefixes from the Map:
List<String> sortedIPV4s = sortListOfIpv4s(unsortedIPv4s);
for (String ip : sortedIPV4s) {
String prefix = prefixMap.get(ip);
String originalIp = prefix + ip;
}
Your method could move any prefix to the end of the String, sort the list, and then go through the Strings again and move the prefixes from the end back to the start.
You could implement Comparator:
public class IpComparator implements Comparator<String> {
#Override
public int compare(String ipA, String ipB) {
return doComparison( ipA.substring(1), ipB.substring(1) );
}
}
Then you can use it:
return Collections.sort(unsortedIPv4s, new IpComparator());