Is it incorrect work Collectors.toSet() in JDK 8?

If I run this code:
public class Main {
    public static void main(String[] args) {
        Collection<String> set = new ArrayList<String>();
        set.add("b");
        set.add("a");
        set.add("c");
        set.add("c");
        set.stream().collect(Collectors.toSet());
        System.out.println(set);
I will get [b,a,c,c]. But if I right, previous code should be short form of expression:
public class Main {
    public static void main(String[] args) {
        Collection<String> set = new ArrayList<>();
        set.add("b");
        set.add("a");
        set.add("c");
        set.add("c");
        Collection<String> set2 = new HashSet<>(set);
        System.out.println(set2);
And here, I got [a,b,c]
So, in example 1. Is it incorrect result or I do something wrong?

But, now I think I was wrong and do not understand, when we need use Collectors.toSet(). Before that, I think the toSet() method, need for returned without duplicates and completing sorting form [a,b,c], and after I thought I will get [a,b,c] in ArrayList.
Thanks for explaining what you were confused about. Now it is very simple.
This line of code WILL produce a set and that set will NOT contain duplicates.
set.stream().collect(Collectors.toSet());
But you are NOT assigning that new set to any variable. If you want to replace the 'set' variable will the new set do an assignment:
set = set.stream().collect(Collectors.toSet());
To see the difference add a couple more lines to your code:
        Collection<String> set = new ArrayList<String>();
        Collection<String> set1 = new ArrayList<String>(); // new collection
        set.add("b");
        set.add("a");
        set.add("c");
        set.add("c");
        set.toArray();
        set.stream().collect(Collectors.toSet());
        set1 = set.stream().collect(Collectors.toSet());
        System.out.println(set);
        System.out.println(set1);
What does that second 'println' produce?
That code assigns the new set to a new collection.
Were you trying to follow and understand the Java Tutorials trail for 'The Set Interface'?
http://docs.oracle.com/javase/tutorial/collections/interfaces/set.html
The example there contains code just like yours:
Here's a simple but useful Set idiom. Suppose you have a Collection, c, and you want to create another Collection containing the same elements but with all duplicates eliminated. The following one-liner does the trick.
Collection<Type> noDups = new HashSet<Type>(c); 
It works by creating a Set (which, by definition, cannot contain duplicates), initially containing all the elements in c. It uses the standard conversion constructor described in the The Collection Interface section.
Or, if using JDK 8 or later, you could easily collect into a Set using aggregate operations:
c.stream().collect(Collectors.toSet()); // no duplicates 
Unfortunately that code has the same flaw yours does. It does, indeed, show that you can 'easily collect into a Set using aggregate operations'. But it doesn't capture that new set anywhere. That might give the impression that the 'c' collection somehow gets modified; but it doesn't.

Similar Messages

  • SQLDeveloper 2.1.62 *still* doesn't work with 64-bit JDK.

    I'm running on Windows XP 64-bit, if I try to make SQLDeveloper use a 64-bit JDK it fails.
    I get this in the console:
    WARNING: Cannot find default VM "client" at D:\progs\Java\jdk1.6.0_16
             using server instead.
    Error: Error loading: D:\progs\Java\jdk1.6.0_16\jre\bin\server\jvm.dll

    Hi Jim,
    Thats right. The exe doesn't support 64bit JDK on Windows yet. It works on other platforms but not Windows. The launcher has to be rebuilt with a 64bit compiler. We're hoping to get this done by production.
    bug 8964980
    Barry

  • Problems in Working with J2me----- call jdk packages in j2me

    Hi guys,
    I am developing an application to compress mp3 in cell phone. I have developed a code using javax.sound and other jdk packages
    Th problem is that i want to call the functions of this code in the J2me code but it give me a error that the jdk packages not found
    So the question is there any way to use JDk packages in J2me
    Waiting for your Reply
    Thnx

    punit_solanki wrote:
    So the question is there any way to use JDk packages in J2meNo, there isn't. But if it is simple, you can try to implement the part of the JDK you use that it is not on J2ME.
    If you want to develop for J2ME, you should use an IDE that sets the configuration for J2ME and doesn't allow you to use libraries that are not on J2ME.
    Netbeans, for example, let you choose which mobile configuration are you going to develop for.

  • Passport BB10.3 Calendar Conference Meeting dialing incorrectly (works on Z30 with 10.2)

    Got my new Passport, and did the "new device" process in an upto date BB Link.  Looks great! But, we use Microsoft Lync as our phone system, and Lync conference calls are not joinable.  When I open the calendar, and click the call phone icon, it dials but gives me the network "cannot complete as dialed" with the SIT tones.
    The exact same meetings come in on my personal Z30 (running Rogers Canada latest 10.2 OS), and it works fine.
    I can see the problem: On the Passport the phone number is duplicated.  When I look at the "Join now" where I click to dial the bridge, the phone number is in there twice.  On my Z30, it is in there only once.
    I get the same calendars on both phones since I have setup my work email on both phones.
    This is a huge issue as my new Passport that I got for work cannot be used for any of my internal company conference calls!!

    Hi davidhealing,
    I can confirm that when using OS 10.3 on a supported device such as the BlackBerry Passport the Evernote integration with the Remember application works without issue.
    You can try reintegrating the account via Settings > Accounts: delete the Evernote integration and re-add the account. This will force a sync of all of your Evernote notebooks to the device. As there isn't much in the way of options available for the Remember integration that would cause sync issues, forcing a re-sync via new integration may help.
    One thing to remember is that you may be encountering a potential issue due to unsupported software, since OS 10.3 has not been released for the BlackBerry Z10 smartphone.
    Did someone help you? Click Like! Did a post solve your issue? Click Accept as Solution!

  • EA2 - incorrect working in XLS import?

    In XLS import, data types tab, the question is "Choose Data Type", but it seems that the question really being asked is "Choose Column Name", since if you click on it you get a pulldown list of column names and not data types.

    um, that should be incorrect question in XLS import

  • Prime Infrastructure 1.3 - Incorrect work with latest version of Addobe Flash Player.

    Good day!
    I try to view all information about user who associated to Wireless Controller in Cisco Prime Infrastructure 1.3, but all browsers that I use (Firefox 20.0.1, Chrome 26.0.1410.64 m) are crash on this step:  
    Does somebody have the same issue?

    Hi Chris
    Adobe have indicated that they have fixed this bug in the Flash Player.  See internal bug number https://bugbase.adobe.com/index.cfm?event=bug&id=3169988.
    I was wondering if its possible to get a beta version of the FLash Plugin with this fix from Adobe.
    Also have you when the next public release of the player is planned with this fix? As I understand it was targetted for version 11.4. Can you confirm if thats the case and when 11.4 is scheduled for release.
    Thanks
    Declan

  • Tomcat + JDK = Not Working

    Thanks to all for at least viewing my topic...
    First off, I am running Linux Mandrake 8.0, here are the specs:
    Apache: Apache 1.3.19
    JDK: jdk-1.3.1-fcs
    Tomcat: tomcat-3.1-3k
    I've been running apache as a stable server for, oh, about 3 months now. I am hosting multiple websites and one of my clients asked me, "Is JSP supported?" so I tried an example JSP page and it didn't work.
    I installed jdk and then Tomcat but for some reason, the TOMCAT daemon won't startup as supposed to... It just says this:
    [root@skynet conf]# service tomcat start
    Starting tomcat:
    [root@skynet conf]#
    Doesn't start. So I don't know where the error is... these were installed in RPM's, not tar's.
    Any help would be much obliged, email me: [email protected]
    Jamie Savard
    Elite Innovations

    somebody please help me.
    i have installed jdk1.2.2
    Tomcat3.2.1
    oracle 8.1.7
    My path settings are
    JAVA_HOME=c:\jdk1.2.1
    TOMCAT_HOME=c:\tomcat\tom3.2.1
    running on windows98
    when i try to start Tomcat i get the following error
    Using CLASSPATH:
    Bad command or file name
    Out of environment space
    Out of environment space
    Out of environment space
    Out of environment space
    Out of environment space
    Unable to set CLASSPATH dynamically.
    Note: To set the CLASSPATH dynamically on Win9x systems
    only DOS 8.3 names may be used in TOMCAT_HOME!
    Setting your CLASSPATH statically.
    Out of environment space
    Out of environment space
    Out of environment space
    Out of environment space
    Out of environment space
    Out of environment space
    Out of environment space
    Using CLASSPATH:
    Bad command or file name
    Please help me what i need to do. I'm new to this environment.

  • How to create HTTPS or secure Socket objects in JDK 1.4?

    I would like to see sample working code that shows creation
    of Sockets objects that work with HTTPS using JDK 1.4. I am doing
    a POST operation (form submission) on HTTPS URL. I must use Socket
    objects and cannot use URLConnection (I know URLConnection solves the problem automatically in JDK 1.4).
    Also sample code for POST operation would be appreciated.

    I wrote this a little while ago to test out Secure Sockets in 1.4. I assume you are doing the client since you are trying talk to a website or something like that, anyway this test class is tested and works, but you will have to clean it up.
    Pup
    import java.io.*;
    import java.security.*;
    import javax.net.ssl.*;
    public class HelloClientSSL {
        public static void main(String[] args) {
            try {
                int port = 8005;
                int tempport =0;
                if(args.length > 1) {
                    try {
                        tempport = Integer.parseInt(args[1]);
                        port = tempport;
                    catch (Exception e) {
                        System.out.println("Sorry this is not a valid number " + args[1]);
                        System.out.println("Using Default port 8005");
                Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());           
                SSLSocketFactory sslFact = (SSLSocketFactory)SSLSocketFactory.getDefault();
                SSLSocket s = (SSLSocket)sslFact.createSocket(args.length == 0 ? "127.0.0.1" : args[0], port);
                s.setEnabledCipherSuites(s.getSupportedCipherSuites());
                java.net.Socket n = (java.net.Socket) s;
                java.io.ObjectOutputStream OOS = new java.io.ObjectOutputStream(n.getOutputStream());
                BufferedReader in = new BufferedReader (new InputStreamReader(n.getInputStream()));
                String response = "";
                String temp = "This is reall cool and stuff\n";
                OOS.writeObject(temp);
                OOS.writeObject("Hello\n");
                while((response =in.readLine()) != null){
                    System.out.println("Socket message: " + response);
                in.close();
            } catch (Exception e) {
                System.out.println("Exception" + e);
                e.printStackTrace();
    }

  • Does the Communications API work with Studio 4

    I just installed Studio 4 along with the JDK. The Java version that I am running now is:
    java version "1.4.1_02"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.1_02-b06)
    Java HotSpot(TM) Client VM (build 1.4.1_02-b06, mixed mode)
    Running on MS XP.
    The Communications API seemed to work just fine on JDK 1.3 with Forte 1.0.
    I installed the Comm API as instructed and set my ClassPath:
    CLASSPATH=D:\PROGRA~1\s1studio_jdk\j2sdk1.4.1_02\lib\comm.jar;D:\MyProjects\java\GarxFace
    A call to:
    Enumeration portList;
    portList = CommPortIdentifier.getPortIdentifiers();
    does not yield any ports at all.
    Stranger yet, if I use the auto complete feature in the editor. For example if I type: m_PortID. then no members of PortID show up.
    But the code compiles just fine.
    Any idea what is going on?

    First I found the reason that the auto complete was not working. I had to mount the comm.jar file (you did not have to do this in Forte 1,0, just set the classpath). I thought that I had done that. That is the problem when you work late. ;)
    Here is a eexcerpt that I found on a search in another post:
    Copy javax.comm.properties to your <JDK>\lib directory.
    C:\>copy c:\commapi\javax.comm.properties c:\jdk1.1.6\lib
    The javax.comm.properties file must be installed. If it is not, no ports will be found by the system.
    Notice it says that "javax.comm.properties file must be installed"
    javax.comm.properties is indeed installed in my JDK lib subrirectory, but it is almost like it is not being found.

  • JDK 1.6.0_21 plugin ?

    well....not working...from jdk-6u21-linux-i586.bin
    libjavaplugin_oji.so conflicts with libnpjp2.so so I left links to libjavaplugin_oji.so into /usr/lib/iceweasel/plugins and put links to libnpjp2.so into /usr/lib/mozilla/plugins and /usr/lib/firefox/plugins....
    this way iceweasel works as expected... but no way with FF4...
    As I need to work with standard SE (and no sun-java nor openjdk) I think I will have to revert to FF 3.6...
    Am I missing something ?

    I suddenly started getting errors like " Plugin instance for applet ID 1 was already released" in Firefox 3.6.11 under Gentoo with the sun 1.6.22 plugin. I was dead in the water. Manually clearing the Cache directory under my ~/.mozilla profile directory corrected it. I have no clue what it was caching (I even had cache disabled with the Web Developer addon at the time), but it was breaking java bigtime...WTF?
    Tom

  • Problem after deinstallation of JDK during SAP System running....

    Hello...
               I am working as a SAP BASIS trainee.I am facing some problem related with java and SAP System.
    Actually an SAP System was already  running on the my system and suddenly i required to work on eclips (an IDE for java). And to install eclips it required JDK 1.6 version.But as we know that for SAP System an JDK 1.4 version required only.
                   I forgot and deinstalled JDK 1.4 and Installed JDK 1.6. and again tryied to installed eclips bt it was still throwing an error that it required JDK 1.6 and currently JDK 1.4 is running.
      On the other hand SAP System was getting problem during SAP START (  dialog queue waiting time elapsed .......). and finally not working.
       I deinstalled JDK 1.6.  now SAP System is working fine. It is getting started and everything is right.
    Could i get any problem latter regarding to SAP Start??and why i cant use eclips on the same system??
    Thanks in advance.
    Uttam Kumar.

    > Could i get any problem latter regarding to SAP Start??and why i cant use eclips on the same system??
    You need to make sure that the SAP system uses the correct JDK. You can install two JDKs in parallel (don't upgrade but install the 1.6 JDK in a separate directory).
    Anyway, NWDI should not be installed on the server but on a local workstation.
    Markus

  • InsertBeforeEnd works in JDK1.3 but not in JDK1.4

    Any idea why this would work perfectly in JDK1.3 but not JDK1.4?
    logPane = new JEditorPane();
    logPane.setEditable(false);
    HTMLEditorKit k = new HTMLEditorKit();
    doc = (HTMLDocument)k.createDefaultDocument();
    logPane.setEditorKit(k);
    logPane.setDocument(doc);
    logPane.setText("<div id=\"myDiv\"></div>");
    Element convDiv = doc.getElement("myDiv");
    doc.setInnerHTML(convDiv,"<p>Test1</p>"); // This works in both
    doc.insertBeforeEnd(convDiv,"<p>Test2</p>"); // This throws exception
    The setInnerHTML works fine in the JDK's. The insertBeforeEnd throws a "BadLocationException: Invalid insert" in JDK1.4 but works fine in JDK1.3...
    Quite frustrating!

    Well, I finally took a look at the JDK code (GapContent.java). It seems the supposedly "fixed" bug is still there in JDK1.4.0 and JDK1.4.1 (latest) (http://developer.java.sun.com/developer/bugParade/bugs/4496801.html)
    The workaround is to put some characters after the div as follows:
    logPane.setText("<div id=\"myDiv\"></div>&_nbsp_;");
    ( remove the _ in nbsp above )
    Now it works in both JDK's!

  • Windows Event Collector - Built-in options for load balancing and high availability ?

    Hello,
    I have a working collector. config is source initiated, and pushed by GPO.
    I would like to deploy a second collector for high availability and load balancing. What are the available options ? I have not found any guidance on TechNet articles.
    As a low cost option, is it fine to simply start using DNS round-robin with a common alias for both servers pushed as a collector name through GPO ?
    In my GPO Policy, if I individually declare both servers, events are forwarded twice, once for each server. Indeed it does cover high availability, but not really optimized.
    Thanks for your help.

    Hi,
    >>As a low cost option, is it fine to simply start using DNS round-robin with a common alias for both servers pushed as a collector name through GPO ?
    Based on the description, we can utilize DNS round robin to distribute workloads and increase fault tolerance. By default, DNS uses round robin to rotate the order of RR data returned in query answers where multiple RRs of the same type exist for a queried
    DNS domain name. This feature provides a simple method for load balancing client use of Web servers and other frequently queried multihomed computers. Besides, by default, DNS will perform round-robin rotation for all RR types.
    Regarding DNS round robin, the following article can be referred to for more information.
    Configuring round robin
    http://technet.microsoft.com/en-us/library/cc787484(v=ws.10).aspx
    TechNet Subscriber Support
    If you are TechNet Subscription user and have any feedback on our support quality, please send your feedback here.
    Best regards,
    Frank Shen

  • Porting from JDK 1.2.2 to MS SDK for Java 4.0 - Help!!!

    Hi All!
    My company is developing big project using WLS 4.5.1. + JDK 1.2.2 + Java
    Plug-In 1.2.2 on clients. A lot of applied code depend on Java 2 APIs,
    javax/swing is actively used as well. But the customer decide to use
    Microsoft VM both on server and client sides - they have support contract
    (for other products) with MS and MS may decide to cancel support if our
    customer will use Sun JDK and Sun JVM.
    So, I have to try to port all project to MS SDK for Java and the question
    is: Do I have a chance not to rewrite 100% of my code?
    Somewhere I read: ":I've downloaded the new MS Virtual Machine
    (msjavx86.exe) that should be compatible to Java2:" - is it really so? Does
    anybody knows if MS will support Java 2 platform specifications? As I found
    at MS, latest MS JDK 4.0 (on which WLS 5.1 can run) meets specification of
    Java 1.1 and after installing it I found that I must rewrite about 90% of my
    code. Can someone clarify the situation with MS JDK?
    Thanks in advance,
    Andrey Bogush
    PS: Any information, links, documents, overviews on how to persuade the
    customer to use Sun JDK and JVM against MS one are VERY and STRONGLY welcome

    Andrey Bogush wrote:
    >
    Hi All!
    My company is developing big project using WLS 4.5.1. + JDK 1.2.2 + Java
    Plug-In 1.2.2 on clients. A lot of applied code depend on Java 2 APIs,
    javax/swing is actively used as well. But the customer decide to use
    Microsoft VM both on server and client sides - they have support contract
    (for other products) with MS and MS may decide to cancel support if our
    customer will use Sun JDK and Sun JVM.MS can cancel their support if they use Sun's JDK! That's an
    "interesting" clause in your support contract.
    >
    So, I have to try to port all project to MS SDK for Java and the question
    is: Do I have a chance not to rewrite 100% of my code?
    Somewhere I read: ":I've downloaded the new MS Virtual Machine
    (msjavx86.exe) that should be compatible to Java2:" - is it really so?I don't believe any versions of Microsoft's JVMs support Java2.
    Personally, I think it would be a big waste of time to port working
    Java2 code to JDK 1.1 just to run MS's JVM.
    -- Rob
    Does
    anybody knows if MS will support Java 2 platform specifications? As I found
    at MS, latest MS JDK 4.0 (on which WLS 5.1 can run) meets specification of
    Java 1.1 and after installing it I found that I must rewrite about 90% of my
    code. Can someone clarify the situation with MS JDK?
    Thanks in advance,
    Andrey Bogush
    PS: Any information, links, documents, overviews on how to persuade the
    customer to use Sun JDK and JVM against MS one are VERY and STRONGLY welcome

  • JAXP: code works with JDK1.3.1/Xerces but not JDK1.4.1

    Switching from JDK 1.3.1 with the Xerces XML parser to JDK 1.4.1 with its
    bundled XML parser breaks my code. Here is the exception I am
    seeing:
    Exception in thread "main" com.post.bean.BeanException com.post.bean.Bea
    nException: Relative URI "bean.dtd"; can not be resolved without a base URI.
    at com.post.bean.BeanSerializer.deserialize(BeanSerializer.java:176)
    at com.post.BeanSerializer1.deserialize(BeanSerializer1.java:38)
    at com.post.BeanSerializer1.main(BeanSerializer1.java:17)
    Here is a code fragment that worked fine with JDK1.3.1 and xerces but
    not with JDK1.4.1:
    public static Object deserialize(InputStream input, EntityResolver
    resolver)
    throws BeanException
    Object bean = null;
    try
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);
    factory.setNamespaceAware(false);
    DocumentBuilder builder = factory.newDocumentBuilder();
    if (resolver != null)
    builder.setEntityResolver(resolver);
    Document doc = builder.parse(input); // exception thrown here
    Element root = doc.getDocumentElement();
    The entity resolver I'm using searches for dtds in
    a certain directory. Again this works fine with JDK1.3.1
    and Xerces but not with JDK1.4.1.
    Any ideas on how to remedy this situation?
    Thanks

    this generally happens when two similar libs conflict with each other. Try any of theses quick fixes: (Remember, 90% of probs in java are Classpath, packages and directory structure issues)
    1. remove completely your previous version of JDK and Xerces.
    2. Remove your classpath variable from system path.
    3. Have "only the required" jar files during compilation. For this use the -D option.
    4. If everything fails, download ANT. Write a simple build.xml file. This is a good replacement to the -D option. But make sure, you are working in a clean JDK environment. Try to monitor your classpaths at run time, and get rid of all the unnecessary once.
    5. MAke sure that Xerces libs bundled with 1.4 are in your classpath at runtime.
    Finally All the best, and happy XMLing+Javing !!
    Rakesh

Maybe you are looking for