Is this correct method to sort ArrayList?
The problem is that the list is not sorted.
out = new StringTokenizer(input.toString());
n = (out.countTokens());
for (int i = 0; i < n; i++) {
String[] words = { out.nextToken().toString() };
final List<String> wordList = Arrays.asList(words);
Collections.sort(wordList);
System.out.println(wordList.toString());
}
Each of your words[] arrays is composed of a single string, obtained from the next token of your StringTokenizer. And you are iterating in exact order of the tokenization. So yes, your output will not be sorted. I presume you wanted to do something like this:
out = new StringTokenizer(input.toString());
int count = out.countTokens():
List<String> wordList = new ArrayList<String>(count);
for(int i = 0; i < count; i++) {
wordList.add(out.nextToken());
}
Collections.sort(wordList);
But, don't use the tokenizer class, its legacy. The following code will serve you better:
List<String> wordList = Arrays.asList(input.split("\\s"));
Collections.sort(wordList);
out.nextToken().toString() give you one string. Your array length should be 1, I presume.
Even if you put this into a loop, you sort at each loop, you have to sort outside the loop.
StringTokenizer out = new StringTokenizer( input.toString());
List<String> wordList = new ArrayList< String >();
while( out.hasMoreTokens()) {
wordList.add( out.nextToken());
}
Collections.sort( wordList );
System.out.println(wordList.toString());
Related
I was trying to test my skills and I try to do a test.
I receive the following input:
[7,11,10,6,9]
[21,24,25,23,26]
[116,115,117,120,121,119]
I need to sort all these values.
I try to do the following:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] parts = null;
List<String> linhas = new ArrayList<>();
for (int i = 0; i < 3; i++) {
String line = br.readLine();
line = line.replace("[","");
line = line.replace("]","");
line = line.replace(" ","");
System.out.println(line);
parts = line.split(",");
}
This way I got to show the output
7,11,10,6,9
21,24,25,23,26
116,115,117,120,121,119
The "String[parts]" got all values, but I don't know how to sort it, because the "parts" parameter is inside a "for loop".
How can I convert it to int/Integer and sort each line?
Assuming [7,11,10,6,9] be the input, we can try converting to a list of integers, and then sort that list:
String input = "[7,11,10,6,9]";
input = input.replaceAll("\\[(.*)\\]", "$1");
String[] vals = input.split(",");
List<Integer> output = Arrays.stream(vals)
.map(v -> Integer.parseInt(v))
.collect(Collectors.toList());
Collections.sort(output);
System.out.println(Arrays.toString(output.toArray()));
This prints:
[6, 7, 9, 10, 11]
Once you have parts you must convert this String[] into an int[]. To do this, first create an int[] for your results to go in. It must be the same size as your String[]:
int[] ints = new int[parts.length];
Then, iterate through the String[] and fill in values in the int[]:
for (int i = 0; i < parts.length; i++) {
ints[i] = Integer.parseInt(parts[i]); // converts a string containing an integer into its int value
}
Finally, to sort each line, a simple call to Arrays.sort(ints); will sort your array of integers.
Bonus:
This can be achieved more cleanly in a single line using Java 8 Streams, as follows:
List<Integer> sortedInts = Arrays.stream(parts).map(Integer::parseInt).sorted().collect(Collectors.toList());
You can do the replace() lines at once and split more cleanly with a regex:
parts = line.split("[\\[\\], ]+");
and use the Iterable technique that cameron1024 demonstrates in his answer. I think that using Iterable is a better choice for this use case than using Streams because the input size is trivially small and Streams has to spend more time to spin up.
The whole thing would look like:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] parts;
List<String> linhas = new ArrayList<>();
for (int i = 0; i < 3; i++) {
String line = br.readLine();
parts = line.split("[\\[\\] ,]+");
}
int ints[] = new int[parts.length];
for(int i = 0; i < parts.length; i++){
ints[i] = Integer.parseInt(parts[i]);
}
Arrays.sort(ints);
I have a String - "Hello#World#Good#Morning"
I want to add alternate words to a string array. Example, from the above string, i should add only Hello and good to my new array.
for (String s : StringsTokens) {
myStringArray = s.split(Pattern.quote("#"));
}
How do i add only alternate elements to string array.
Looking at the patter you need to add words located at even positions.
So after splitting the string with the below code, to get a string array:
String[] words = string.split("#");
And initialising an ArrayList to use in your loops:
ArrayList<String> arList = new ArrayList<>();
you will run a for loop with :
for (int i=0 ; i<words.length ; i+=2) {
// store the words in ArrayList like
arList.add(words[i]);
}
//Convert ArrayList to Array and re-initialise ArrayList for the next String
String[] newArray = arList.toArray();
arList = new ArrayList<String>();
Try with this:
List<String> result = new ArrayList<>();
String[] src = "Hello#World#Good#Morning".split( "#" );
for ( int i=0 ; i < src.length ; i++ ) {
if( i%2 == 0 ) {
result.add( src[i] );
}
}
System.out.println(result);
output: [Hello, Good]
I want to make a for-loop to add a letter to each string object in my list. I'm just not sure how to edit the objects in the list and not the actual list.
for instance, if I wanted to add "ing" to the end of each object in my list..
I feel like it's something simple, but I've been looking through oracle forever and haven't been able to figure it out if anyone can point me in the right direction?
I could use any kind of list really.. just anything that works.
I was thinking something like,
String[] stringArray = tools.toArray(new String[0]);
for (int i = 0; i < stringArray.length; i++)
{
stringArray[i] = stringArray[i].*part that would modify would go here*
}
You cannot edit a String. They are immutable. However, you can replace the entry in the list.
ArrayList<String> list = new ArrayList<>();
list.add("load");
list.add("pull");
for (int i = 0; i < list.size(); ++i) {
list.set(i, list.get(i) + "ing");
You updated your question to specify a static array:
stringArray[i] = stringArray[i] + "ing";
The right side of the assignment is performing a String concatenation which can be done with the + operator in Java.
You can use StringBuilder for this purpose.
public static void addIng(String[] arr) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < arr.length; i++) {
sb.setLength(0);
sb.append(arr[i] + "ing");
arr[i] = sb.toString();
}
}
Strings are immutable in java; they can't be modified once created.
Here it seems you have a few options; you can create a method that takes your list and returns a new list, by appending 'ing' to the end of each string in the list.
Alternatively, if you need to keep a reference to the original list, you can loop over the contents of the list (ArrayList?) and pop each string out, create a new string with the appended 'ing', and replace in the list.
Something like
List<String> list = new ArrayList<>();
list.add("testing");
for(String s:list){
s=s+"ing";
}
Please take a look below samples.
//Java 8 code.
List<String> oldList = Arrays.asList("a", "b");
List<String> newList = oldList.stream().map(str -> new StringBuilder(str).append("ing").toString()).collect(Collectors.toList());
System.out.println(oldList); // [a, b]
System.out.println(newList); // [aing, bing]
// Java 7 or below.
List<String> oldList = Arrays.asList("a", "b");
List<String> newList = new LinkedList<String>();
for (String str : oldList) {
newList.add(new StringBuilder(str).append("ing").toString());
}
System.out.println(oldList); // [a, b]
System.out.println(newList); // [aing, bing]
I am trying to remove duplicated words from an array, and I keep getting null values. I'm not allowed to use java sorting methods so I have to develop my own. Here's my code:
public class Duplicate{
public static void main(String[] args){
String[] test = {"a", "b", "abvc", "abccc", "a", "bbc", "ccc", "abc", "bbc"};
removeDuplicate(test);
}
public static String[] removeDuplicate(String[] words){
boolean [] isDuplicate = new boolean[words.length];
int i,j;
String[] tmp = new String[words.length];
for (i = 0; i < words.length ; i++){
if (isDuplicate[i])
continue;
for(j = 0; j < words.length ; j++){
if (words[i].equals(words[j])) {
isDuplicate[j] = true;
tmp[i] = words[i];
}
}
}
for(i=0;i<words.length;i++)
System.out.println(tmp[i]);
return tmp;
}
}
I tried doing
if(words == null)
words == "";
But it doesn't work. I also want to return the tmp array with a new size.
For example, test array length = 9, after removing the duplicates,I should get a new array with a length of 7.Thank you for your help.
EDIT:
result i get:
a
b
abvc
abccc
null
bbc
ccc
abc
null
You're getting nulls because the result array contains fewer words than the input array. However, you're constructing the arrays of the same length.
You don't have to sort to solve this problem. However, if you're not allowed to use the tools provided by java.utils, then this is either a poorly contrived test question or whomever told you not to use the Java utility classes is poorly informed.
You can solve without sorting by doing (assuming Java 1.5+):
public class Duplicate {
public static void main(String[] args) {
String[] test = {"a", "b", "abvc", "abccc", "a", "bbc", "ccc", "abc", "bbc"};
String[] deduped = removeDuplicate(test);
print(deduped);
}
public static String[] removeDuplicate(String[] words) {
Set<String> wordSet = new LinkedHashSet<String>();
for (String word : words) {
wordSet.add(word);
}
return wordSet.toArray(new String[wordSet.size()]);
}
public static void print(String[] words) {
for (String word : words) {
System.out.println(word);
}
}
}
The output will be:
a
b
abvc
abccc
bbc
ccc
abc
I would go for hashset to remove duplicates, it will remove duplicates since hash function for the same string will give same value, and duplicates will be eliminated. Then you can convert it to a string.
I would recommend doing this with a different approach. If you can use an ArrayList, why not just create one of those, and add the non-duplicate values to it, like this:
ArrayList<String> uniqueArrayList = new ArrayList<String>();
for(int i = 0; i < words.length; i++){
if(!uniqueArrayList.contains(words[i])){ // If the value isn't in the list already
uniqueArrayList.add(words[i]);
}
}
Now, you have an array list of all of your values without the duplicates. If you need to, you can work on converting that back to a regular array.
EDIT
I really think you should use the above option if you can, as there is no clean or decently efficient way to do this only using arrays. However, if you must, you can do something like this:
You can use the code you have to mark values as null if they are duplicates, and also create a counter to see how many unique values you have, like this:
int uniqueCounter = 0;
for(int i = 0; i < isDuplicate.length; i++){
if(!isDuplicate[i]){
uniqueCounter++;
}
}
Then, you can create a new array of the size of unique items, and loop through the words and add non-duplicate values.
String[] uniqueArray = new String[uniqueCounter];
int uniqueIndex = 0;
int wordsIndex = 0;
while(index < uniqueArray.length){
// Check if words index is not a duplicate
if(!isDuplicate[wordsIndex]){
// Add to array
uniqueArray[uniqueIndex] = words[wordsIndex];
uniqueIndex++; // Need to move to next spot in unique.
}
// Need to move to next spot in words
wordsIndex++;
}
Again, I HIGHLY recommend against something like this. It is very poor, and pains me to write, but for the sake of example on how it could be done using an array, you can try it.
I don't have the time to write functioning code, but I would reccomend to first sort the array using Arrays.sort(stringArray) and then loop throug the array coparing one string to the previous. Strings that match the previous one are duplicates.
Note: This method is probably not the fastest one and though only should be used on small arrays or in tasks where performance does not matter.
What about this approach?
public static String[] removeDuplicate(String[] words){
// remember which word is a duplicate
boolean[] isDuplicate = new boolean[words.length];
// and count them
int countDuplicate = 0;
for (int i = 0; i < words.length ; i++){
// only check "forward" because "backwards checked" duplicates have been marked yet
for(int j = i + 1; j < words.length ; j++){
if (words[i].equals(words[j])) {
isDuplicate[j] = true;
countDuplicate++;
}
}
}
// collect non-duplicate strings
String[] tmp = new String[words.length - countDuplicate];
int j = 0;
for (int i = 0; i < isDuplicate.length; i++) {
if (isDuplicate[i] == false) {
tmp[j] = words[i];
j++;
}
}
// and return them
return tmp;
}
I have to split off the last two characters of an ID, the id may vary in length. example 56427R1 and R00220P3. Once the last two characters are split off, I need to add the first set of characters and the last two characters to an ArrayList. Thanks in advance.
I've tried the following
List<String> list = new ArrayList<String>();
list.add(clientValue.substring(0, clientValue.length()-2));
but was having trouble keeping the last 2 characters while removing the first half.
Resolved, repaired with the following code
ArrayList<String> list = new ArrayList<String>();
list.add(clientValue.substring(clientValue.length()-2));
list.add(clientValue.substring(0, clientValue.length()-2));
Use String.substring() with String.length() to split the string.
Use ArrayList<String>.add() to append to an ArrayList.
EDIT:
the code you have posted is correct: clientValue is not modified by the call to clientValue.substring() but returns a new String instance. Java String are immutable.
To complete your code:
List<String> list = new ArrayList<String>();
list.add(clientValue.substring(0, clientValue.length()-2));
list.add(clientValue.substring(clientValue.length()-2));
string tmp = "56427R1";
ArrayList<String> arrList = new ArrayList()<String>;
arrayList.add(tmp.substring(tmp.length() - 2));
arrayList.add(tmp.substring((tmp.length() - 2), tmp.length()));
You can do it easily like this:
String myID = "56427R1";
String extractedID = myID.substring((myID.length()-2), myID.length());
ArrayList<String> list = new ArrayList<String>;v
list.add(myID.substring((myID.length()-2)));
list.add(extractedID);
UPDATE:
String myID = "56427R1";
String extractedID = myID.substring((myID.length()-2), myID.length());
char[] a = extractedID.toCharArray();
char[] b = myID.substring(myID.length()-2).toCharArray();
ArrayList<Character> list = new ArrayList<Character>();
for(int i = 0; i < b.length; i++)
list.add(b[i]);
for(int j = 0; j < a.length; j++)
list.add(a[j]);