CINXE.COM

java - Stack Abuse

<!DOCTYPE html><html lang="en"><head><meta charSet="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1.0"/><title>java - Stack Abuse</title><link rel="canonical" href="https://stackabuse.com/tag/java/"/><meta property="og:url" content="https://stackabuse.com/tag/java/"/><meta name="twitter:url" content="https://stackabuse.com/tag/java/"/><link rel="next" href="https://stackabuse.com/tag/java/page/2/"/><meta property="og:site_name" content="Stack Abuse"/><meta property="og:type" content="website"/><meta property="og:title" content="java - Stack Abuse"/><meta name="twitter:card" content="summary"/><meta name="twitter:title" content="java - Stack Abuse"/><meta name="twitter:site" content="@StackAbuse"/><script type="application/ld+json">{ "@context": "https://schema.org", "@type": "Series", "publisher": { "@type": "Organization", "name": "Stack Abuse", "logo": { "@type": "ImageObject", "url": "https://stackabuse.com/assets/images/favicon.svg" } }, "url": "https://stackabuse.com/tag/java/", "name": "java", "mainEntityOfPage": { "@type": "WebPage", "@id": "https://stackabuse.com/" } }</script><meta name="next-head-count" content="14"/><link href="//fonts.googleapis.com" rel="preconnect"/><link href="//fonts.gstatic.com" rel="preconnect" crossorigin="true"/><link href="//cdnjs.cloudflare.com" rel="preconnect"/><link href="//s3.stackabuse.com" rel="preconnect"/><link href="//googletagmanager.com" rel="dns-prefetch"/><meta charSet="utf-8"/><meta http-equiv="X-UA-Compatible" content="IE=edge"/><meta name="HandheldFriendly" content="True"/><link rel="shortcut icon" sizes="any" href="/assets/images/favicon.ico"/><link rel="shortcut icon" type="image/svg+xml" href="/assets/images/favicon.svg"/><link rel="preload" as="style" href="//fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&amp;display=swap"/><link rel="preload" as="style" href="//fonts.googleapis.com/css?family=Nunito:400,400i,700,700i&amp;display=swap"/><meta name="referrer" content="no-referrer-when-downgrade"/><link rel="alternate" type="application/rss+xml" title="Stack Abuse" href="https://stackabuse.com/rss/"/><link rel="preload" href="/_next/static/css/c1478bd5d45865d4.css" as="style"/><link rel="stylesheet" href="/_next/static/css/c1478bd5d45865d4.css" data-n-g=""/><noscript data-n-css=""></noscript><script defer="" nomodule="" src="/_next/static/chunks/polyfills-c67a75d1b6f99dc8.js"></script><script src="/_next/static/chunks/webpack-ee76dfca013d17c3.js" defer=""></script><script src="/_next/static/chunks/framework-1dabaad0401a053e.js" defer=""></script><script src="/_next/static/chunks/main-d8a61e54c9c79897.js" defer=""></script><script src="/_next/static/chunks/pages/_app-c6af215d4c8f5cbb.js" defer=""></script><script src="/_next/static/chunks/c78d26b1-fe043233b220ebfb.js" defer=""></script><script src="/_next/static/chunks/816-dfcc5ef3cff7cadb.js" defer=""></script><script src="/_next/static/chunks/3646-6744b27b8ec60fa7.js" defer=""></script><script src="/_next/static/chunks/7329-ea47eb245049fa3f.js" defer=""></script><script src="/_next/static/chunks/2221-aa293f4e0cf5d5c8.js" defer=""></script><script src="/_next/static/chunks/1901-1adb982ef134be61.js" defer=""></script><script src="/_next/static/chunks/pages/tag/%5B...slug%5D-a3eeaba82413e9b8.js" defer=""></script><script src="/_next/static/1732594514432/_buildManifest.js" defer=""></script><script src="/_next/static/1732594514432/_ssgManifest.js" defer=""></script></head><body><div id="__next"><div><nav class="bg-white pb-2 border-b shadow"><div class="mx-8 px-2 sm:px-4 lg:px-8"><div class="flex justify-between h-16"><div class="flex items-center px-2 lg:px-0"><a href="/"><div class="flex-shrink-0 flex items-center"><svg class="h-6 w-full" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 494.36 63"><defs><style>.cls-1{fill:#363636}.cls-2{fill:#f29c80}.cls-3{fill:#b34a28}.cls-4{fill:#f16335}</style></defs><title>SA Logotype</title><g id="Layer_2" data-name="Layer 2"><g id="Layer_1-2" data-name="Layer 1"><path class="cls-1" d="M104.94,27.65q-3.15-1.44-4.65-2.16c-1-.48-2.17-1.12-3.49-1.91A10.35,10.35,0,0,1,94,21.35a3.58,3.58,0,0,1-.82-2.27,4.79,4.79,0,0,1,1.74-3.89,7.6,7.6,0,0,1,5-1.44,16,16,0,0,1,5.61,1.15,27.13,27.13,0,0,1,4.1,1.84c.73.46,1.3.83,1.71,1.12l5.2-10.8-2-1.44A28.63,28.63,0,0,0,108,2.84a29.37,29.37,0,0,0-9-1.4A18.5,18.5,0,0,0,86.2,6.52a16.81,16.81,0,0,0-5.61,13.06,14.64,14.64,0,0,0,2.81,8.61,21.59,21.59,0,0,0,7.93,6.66c.82.43,2.09,1.07,3.8,1.91s2.94,1.46,3.69,1.87a27.75,27.75,0,0,1,2.6,1.65,6.9,6.9,0,0,1,2,2.09,4.57,4.57,0,0,1,.58,2.27q0,5.84-8.14,5.83a14.52,14.52,0,0,1-6.46-1.87,35.41,35.41,0,0,1-5.1-3c-.95-.74-1.71-1.35-2.25-1.83L75.67,55.15l.89.79a19.23,19.23,0,0,0,2.8,2c1.28.77,2.71,1.55,4.31,2.34a26.52,26.52,0,0,0,6,2,33.14,33.14,0,0,0,7.25.79,29.54,29.54,0,0,0,8-1,21.94,21.94,0,0,0,6.74-3.21,14.53,14.53,0,0,0,4.79-6,21.36,21.36,0,0,0,1.74-8.93,13.77,13.77,0,0,0-3.86-9.54A28,28,0,0,0,104.94,27.65Z"></path><path class="cls-1" d="M143.66,50.69a5.8,5.8,0,0,1-1.17.57,3.84,3.84,0,0,1-1.43.29q-2.75,0-2.74-5.11V34.7h7.39V25h-7.39V11.23H126.21V25h-5.06V34.7h5.06V48.89a22.21,22.21,0,0,0,.55,5,16,16,0,0,0,1.81,4.47,9,9,0,0,0,3.73,3.38A12.76,12.76,0,0,0,138.18,63a17.23,17.23,0,0,0,8.9-2.3l-3-10.3Z"></path><path class="cls-1" d="M177.44,28.51A15.41,15.41,0,0,0,166,23.9a15.82,15.82,0,0,0-12.51,5.69,20.47,20.47,0,0,0-4.93,13.9,20.33,20.33,0,0,0,4.93,13.86A15.85,15.85,0,0,0,166,63a14.47,14.47,0,0,0,11.49-5.26h.14v4.18h12V25H177.44Zm-2,21.17a7.68,7.68,0,0,1-5.85,2.45,7.79,7.79,0,0,1-6-2.41,8.74,8.74,0,0,1-2.26-6.23,8.69,8.69,0,0,1,2.36-6.27,8.15,8.15,0,0,1,11.63,0,8.69,8.69,0,0,1,2.36,6.27A8.74,8.74,0,0,1,175.43,49.68Z"></path><path class="cls-1" d="M216.43,34.34a9.4,9.4,0,0,1,5.88,1.73l4.11-8.71-1.16-.86a15,15,0,0,0-4.18-1.73,22.57,22.57,0,0,0-6.43-.87,18.72,18.72,0,0,0-13.57,5.8,18.81,18.81,0,0,0-5.85,13.86,18.52,18.52,0,0,0,5.85,13.72A18.83,18.83,0,0,0,214.65,63a22,22,0,0,0,6.54-.94,20,20,0,0,0,3.89-1.47c.57-.36,1-.66,1.34-.9l-4.11-8.86-.61.43a9.12,9.12,0,0,1-2.16.87,10.87,10.87,0,0,1-3.11.43,7.75,7.75,0,0,1-5.88-2.66,9.22,9.22,0,0,1-2.46-6.48A9.1,9.1,0,0,1,210.55,37,7.72,7.72,0,0,1,216.43,34.34Z"></path><polygon class="cls-1" points="271.43 24.98 255.69 24.98 243.45 37.87 243.45 0 231.34 0 231.34 61.92 243.45 61.92 243.45 47.16 257.47 61.92 273.07 61.92 254.74 42.62 271.43 24.98"></polygon><polygon class="cls-1" points="296.96 2.52 274.18 61.92 288 61.92 302.84 20.88 302.98 20.88 317.82 61.92 331.63 61.92 308.86 2.52 296.96 2.52"></polygon><path class="cls-1" d="M357.42,23.9a15.41,15.41,0,0,0-11.49,4.61V0H333.82V61.92h12V57.74h.14A14.47,14.47,0,0,0,357.42,63a15.88,15.88,0,0,0,12.52-5.65,20.38,20.38,0,0,0,4.92-13.86,20.51,20.51,0,0,0-4.92-13.9A15.86,15.86,0,0,0,357.42,23.9Zm2.33,25.82a7.8,7.8,0,0,1-5.95,2.41A7.65,7.65,0,0,1,348,49.68a8.69,8.69,0,0,1-2.29-6.19A8.64,8.64,0,0,1,348,37.22a7.7,7.7,0,0,1,5.78-2.44,7.78,7.78,0,0,1,5.84,2.44A8.64,8.64,0,0,1,362,43.49,8.78,8.78,0,0,1,359.75,49.72Z"></path><path class="cls-1" d="M405.78,42.55c0,3.65-.53,6.24-1.57,7.78s-2.83,2.3-5.34,2.3-4.29-.77-5.33-2.3S392,46.2,392,42.55V25h-12.1V45.65q0,9.21,4.54,13.28T398.87,63q9.92,0,14.47-4.07t4.55-13.28V25H405.78Z"></path><path class="cls-1" d="M449.11,42.19A20.21,20.21,0,0,0,445.79,40a23.31,23.31,0,0,0-3.69-1.44,8.7,8.7,0,0,1-1-.29c-.44-.14-.74-.25-.93-.32l-.82-.32-.78-.33-.65-.32a2.25,2.25,0,0,1-.58-.4c-.12-.12-.24-.26-.38-.43a1.25,1.25,0,0,1-.27-.54,2.25,2.25,0,0,1-.07-.58,1.82,1.82,0,0,1,.85-1.76,6.53,6.53,0,0,1,2.91-.47,16,16,0,0,1,7.8,2.31l4-8.36-1.43-.72a22.21,22.21,0,0,0-4.38-1.44,24.9,24.9,0,0,0-5.95-.72q-7,0-11.18,3.14a10.32,10.32,0,0,0-4.14,8.74,9.07,9.07,0,0,0,1.91,6,18.12,18.12,0,0,0,5.2,4.06,28.82,28.82,0,0,0,3.59,1.59A14.8,14.8,0,0,1,439,49a2.2,2.2,0,0,1,1,1.9c0,1.78-1.26,2.67-3.76,2.67a9.22,9.22,0,0,1-4-1.19A23.33,23.33,0,0,1,429,50.51c-.6-.46-1.08-.85-1.44-1.19L422.61,58l1.5,1.3A17.63,17.63,0,0,0,429,61.78,21,21,0,0,0,436.15,63q16.62,0,16.62-12.6a11.23,11.23,0,0,0-1-4.75A9.24,9.24,0,0,0,449.11,42.19Z"></path><path class="cls-1" d="M494.36,43.49q0-9.43-5.24-14.51T475.55,23.9a18.46,18.46,0,0,0-13.62,5.76,19,19,0,0,0-5.67,13.83,18.9,18.9,0,0,0,5.67,13.79A18.54,18.54,0,0,0,475.55,63q12.72,0,18.19-9.65L485,48.74a13.63,13.63,0,0,1-3.9,3.28,10.84,10.84,0,0,1-4.65.83,8.3,8.3,0,0,1-5.2-1.87q-2.4-1.87-2.4-5.76h25.45A14.91,14.91,0,0,0,494.36,43.49Zm-25.17-5.33a6,6,0,0,1,1.91-4.32,6.77,6.77,0,0,1,4.79-1.66,6.51,6.51,0,0,1,4.48,1.55,7,7,0,0,1,2.15,4.43Z"></path><polygon class="cls-2" points="66.05 19.08 73.15 1.3 57.25 1.3 50.16 19.08 66.05 19.08"></polygon><polygon class="cls-3" points="40.21 43.99 32.99 62.06 48.88 62.06 56.1 43.99 40.21 43.99"></polygon><polygon class="cls-4" points="57.69 40.01 64.46 23.05 48.57 23.05 41.8 40.01 57.69 40.01"></polygon><polygon class="cls-2" points="33.06 19.08 40.16 1.3 24.27 1.3 17.17 19.08 33.06 19.08"></polygon><polygon class="cls-3" points="7.22 43.99 0 62.06 15.89 62.06 23.11 43.99 7.22 43.99"></polygon><polygon class="cls-4" points="24.7 40.01 31.47 23.05 15.58 23.05 8.81 40.01 24.7 40.01"></polygon></g></g></svg></div></a><div class="hidden lg:block lg:ml-6"><div class="hidden lg:ml-6 lg:flex"><a href="/tools/" class="mr-8 inline-flex items-center px-1 pt-1 border-b-2 border-blue-400 text-sm font-medium leading-10 text-gray-500 hover:text-gray-700 focus:outline-none focus:text-gray-700 transition duration-150 ease-in-out">Tools</a><div class="px-1 pt-1 border-b-2 border-green-400 focus:border-gray-300 transition duration-150 ease-in-out"><div class="relative" data-headlessui-state=""><button class="text-gray-500 group rounded-md inline-flex items-center focus:outline-none text-sm font-medium leading-10 text-gray-500 hover:text-gray-700 hover:border-gray-300 focus:outline-none focus:text-gray-700" type="button" aria-expanded="false" data-headlessui-state=""><span>Learn</span><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true" class="text-gray-400 ml-2 h-5 w-5 group-hover:text-gray-500"><path fill-rule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clip-rule="evenodd"></path></svg></button></div><div hidden="" style="position:fixed;top:1px;left:1px;width:1px;height:0;padding:0;margin:-1px;overflow:hidden;clip:rect(0, 0, 0, 0);white-space:nowrap;border-width:0;display:none"></div></div><a href="/about/" class="ml-8 inline-flex items-center px-1 pt-1 border-b-2 border-red-400 text-sm font-medium leading-10 text-gray-500 hover:text-gray-700 focus:outline-none focus:text-gray-700 transition duration-150 ease-in-out">About</a></div></div></div><div class="hidden mt-4 md:flex md:flex-1 md:items-center md:justify-center md:px-2 lg:ml-6 lg:justify-end"><div class="relative w-1/2 text-gray-400 transition duration-200 focus-within:text-gray-600"><div class="absolute inset-y-0 left-0 flex items-center pointer-events-none" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true" class="h-5 w-5 ml-2"><path fill-rule="evenodd" d="M8 4a4 4 0 100 8 4 4 0 000-8zM2 8a6 6 0 1110.89 3.476l4.817 4.817a1 1 0 01-1.414 1.414l-4.816-4.816A6 6 0 012 8z" clip-rule="evenodd"></path></svg></div><input id="search-field" class="block w-full h-full pl-10 pr-3 py-3 text-sm border-gray-300 text-gray-900 placeholder-gray-500 rounded transition duration-200 focus:outline-none focus:ring-0 focus:border-gray-400" placeholder="Search" type="text"/></div><div class="hidden ml-6 md:flex items-center"><button class="whitespace-nowrap text-base font-medium text-gray-500 hover:text-gray-900">Sign in</button><button class="ml-6 whitespace-nowrap inline-flex items-center justify-center px-4 py-2 border border-transparent rounded-md shadow-sm text-base font-medium text-white bg-orange-500 hover:bg-orange-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-orange-500">Sign up</button></div></div><div class="flex items-center lg:hidden"><button class="inline-flex items-center justify-center p-2 rounded-md text-gray-400 hover:text-gray-500 hover:bg-gray-100 focus:outline-none focus:bg-gray-100 focus:text-gray-500 transition duration-150 ease-in-out" aria-label="Main menu" aria-expanded="false"><svg class="block h-6 w-6" stroke="currentColor" fill="none" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16"></path></svg><svg class="hidden h-6 w-6" stroke="currentColor" fill="none" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg></button></div></div></div><div class="hidden lg:hidden"><div class="pt-2 pb-3"><a href="/tag/python" class="mt-1 block pl-3 pr-4 py-2 border-l-4 border-transparent text-base font-medium text-gray-600 hover:text-gray-800 hover:bg-gray-50 hover:border-gray-300 focus:outline-none focus:text-gray-800 focus:bg-gray-50 focus:border-gray-300 transition duration-150 ease-in-out">Python</a><a href="/tag/javascript" class="mt-1 block pl-3 pr-4 py-2 border-l-4 border-transparent text-base font-medium text-gray-600 hover:text-gray-800 hover:bg-gray-50 hover:border-gray-300 focus:outline-none focus:text-gray-800 focus:bg-gray-50 focus:border-gray-300 transition duration-150 ease-in-out">JavaScript</a><a href="/tag/java" class="mt-1 block pl-3 pr-4 py-2 border-l-4 border-transparent text-base font-medium text-gray-600 hover:text-gray-800 hover:bg-gray-50 hover:border-gray-300 focus:outline-none focus:text-gray-800 focus:bg-gray-50 focus:border-gray-300 transition duration-150 ease-in-out">Java</a></div></div></nav><main><div class="flex items-stretch min-h-screen"><div class="mx-auto max-w-none lg:max-w-screen-xl px-4 sm:px-6 pb-6"><div class="grid grid-cols-12 sm:gap-x-2 lg:gap-x-3 pt-6"><div class="col-span-12 lg:col-span-7"><h1 class="my-1 text-3xl tracking-tight leading-10 font-extrabold text-gray-900 sm:leading-none sm:text-6xl lg:text-4xl xl:text-5xl">java</h1><div class="">Articles: <!-- -->290</div><div class="my-4"></div></div><div class="lg:col-span-1"></div></div><div class="mt-8 border-t border-gray-200"><h2 class="my-6 text-xl tracking-tight leading-10 font-extrabold text-gray-700 sm:leading-none sm:text-4xl lg:text-2xl xl:text-3xl">Recently published</h2><div class="grid gap-5 lg:grid-cols-3"><div><div class="flex flex-col rounded-lg shadow-lg overflow-hidden"><div class="flex-shrink-0"><a href="/how-to-list-all-kafka-topics/"><img class="h-48 w-full object-cover" src="/assets/images/logo-java.png" alt=""/></a></div><div class="flex-1 bg-white p-6 flex flex-col justify-between"><div class="flex-1"><p class="text-sm leading-5 font-medium text-primary">Article</p><a class="block hover:no-underline" href="/how-to-list-all-kafka-topics/"><h3 class="mt-2 text-xl leading-7 font-semibold text-gray-900 hover:underline">How to List All Kafka Topics</h3><p class="mt-3 text-base leading-6 text-gray-500 break-words">If you&#x27;ve stumbled upon this article, chances are you&#x27;ve already been working with Apache Kafka, the open-source distributed streaming platform that has gained significant popularity for its ability to handle large-scale, real-time data processing. In this article, we&#x27;ll dive into the nitty-gritty of managing and monitoring Kafka topics. Topics are...</p></a></div><div class="mt-6 flex items-center"><div class="flex-shrink-0"><a href="/author/scott/"><img class="h-10 w-10 rounded-full" src="//s3.stackabuse.com/media/users/1922fc67b9d11d6364dc01a3d19f4293.jpg" alt="Scott Robinson"/></a></div><div class="ml-3"><p class="text-sm leading-5 font-medium text-gray-900"><a href="/author/scott/" class="hover:underline">Scott Robinson</a></p><div class="flex text-sm leading-5 text-gray-500"><time dateTime="2023-04-19">Apr 19, 2023</time><span class="mx-1">路</span><span>8<!-- --> min read</span></div></div></div></div></div></div><div><div class="flex flex-col rounded-lg shadow-lg overflow-hidden"><div class="flex-shrink-0"><a href="/purging-kafka-topics/"><div class="lazyload-wrapper "><div style="height:12rem" class="lazyload-placeholder"></div></div></a></div><div class="flex-1 bg-white p-6 flex flex-col justify-between"><div class="flex-1"><p class="text-sm leading-5 font-medium text-primary">Article</p><a class="block hover:no-underline" href="/purging-kafka-topics/"><h3 class="mt-2 text-xl leading-7 font-semibold text-gray-900 hover:underline">Purging Kafka Topics</h3><p class="mt-3 text-base leading-6 text-gray-500 break-words">If you&#x27;ve been working with Kafka for a while, you&#x27;re probably aware of the importance of properly managing your Kafka topics. As the backbone of your data streaming infrastructure, well-organized topics can keep your system running smoothly and efficiently, while ensuring that you&#x27;re making the most out of the valuable...</p></a></div><div class="mt-6 flex items-center"><div class="flex-shrink-0"><a href="/author/scott/"><div class="lazyload-wrapper "><div style="height:2.5rem" class="lazyload-placeholder"></div></div></a></div><div class="ml-3"><p class="text-sm leading-5 font-medium text-gray-900"><a href="/author/scott/" class="hover:underline">Scott Robinson</a></p><div class="flex text-sm leading-5 text-gray-500"><time dateTime="2023-04-13">Apr 13, 2023</time><span class="mx-1">路</span><span>9<!-- --> min read</span></div></div></div></div></div></div><div><div class="flex flex-col rounded-lg shadow-lg overflow-hidden"><div class="flex-shrink-0"><a href="/bytes/java-convert-int-to-a-byte/"><div class="lazyload-wrapper "><div style="height:12rem" class="lazyload-placeholder"></div></div></a></div><div class="flex-1 bg-white p-6 flex flex-col justify-between"><div class="flex-1"><p class="text-sm leading-5 font-medium text-primary">Byte</p><a class="block hover:no-underline" href="/bytes/java-convert-int-to-a-byte/"><h3 class="mt-2 text-xl leading-7 font-semibold text-gray-900 hover:underline">Java: Convert Int to a Byte</h3><p class="mt-3 text-base leading-6 text-gray-500 break-words">In Java, an int is a 32-bit signed integer, while a byte is a 8-bit signed integer. Converting an int to a byte can be useful in certain situations, such as when working with binary data or when sending data over a network. In this article, we will explore different...</p></a></div><div class="mt-6 flex items-center"><div class="flex-shrink-0"><a href="/author/scott/"><div class="lazyload-wrapper "><div style="height:2.5rem" class="lazyload-placeholder"></div></div></a></div><div class="ml-3"><p class="text-sm leading-5 font-medium text-gray-900"><a href="/author/scott/" class="hover:underline">Scott Robinson</a></p><div class="flex text-sm leading-5 text-gray-500"><time dateTime="2023-01-24">Jan 24, 2023</time><span class="mx-1">路</span><span>12<!-- --> min read</span></div></div></div></div></div></div><div><div class="flex flex-col rounded-lg shadow-lg overflow-hidden"><div class="flex-shrink-0"><a href="/bytes/java-regular-expressions-validate-ip-addresses/"><div class="lazyload-wrapper "><div style="height:12rem" class="lazyload-placeholder"></div></div></a></div><div class="flex-1 bg-white p-6 flex flex-col justify-between"><div class="flex-1"><p class="text-sm leading-5 font-medium text-primary">Byte</p><a class="block hover:no-underline" href="/bytes/java-regular-expressions-validate-ip-addresses/"><h3 class="mt-2 text-xl leading-7 font-semibold text-gray-900 hover:underline">Java Regular Expressions - Validate IP Addresses</h3><p class="mt-3 text-base leading-6 text-gray-500 break-words">Regular Expressions are widely-applicable and used to match patterns in text, whether for search, validation or other processing. A common way to use them is to check whether a number is valid - i.e. follows a pattern. IP addresses follow a particular pattern, and can be tested with Regular...</p></a></div><div class="mt-6 flex items-center"><div class="flex-shrink-0"><a href="/author/guest/"><div class="lazyload-wrapper "><div style="height:2.5rem" class="lazyload-placeholder"></div></div></a></div><div class="ml-3"><p class="text-sm leading-5 font-medium text-gray-900"><a href="/author/guest/" class="hover:underline">Guest Contributor</a></p><div class="flex text-sm leading-5 text-gray-500"><time dateTime="2023-01-11">Jan 11, 2023</time><span class="mx-1">路</span><span>4<!-- --> min read</span></div></div></div></div></div></div><div><div class="flex flex-col rounded-lg shadow-lg overflow-hidden"><div class="flex-shrink-0"><a href="/bytes/java-regular-expressions-validate-ssn/"><div class="lazyload-wrapper "><div style="height:12rem" class="lazyload-placeholder"></div></div></a></div><div class="flex-1 bg-white p-6 flex flex-col justify-between"><div class="flex-1"><p class="text-sm leading-5 font-medium text-primary">Byte</p><a class="block hover:no-underline" href="/bytes/java-regular-expressions-validate-ssn/"><h3 class="mt-2 text-xl leading-7 font-semibold text-gray-900 hover:underline">Java Regular Expressions - Validate SSN</h3><p class="mt-3 text-base leading-6 text-gray-500 break-words">Regular Expressions are widely-applicable and used to match patterns in text, whether for search, validation or other processing. A common way to use them is to check whether a number is valid - i.e. follows a pattern. SSNs (Social Security Numbers) follow a particular pattern, and can be tested...</p></a></div><div class="mt-6 flex items-center"><div class="flex-shrink-0"><a href="/author/david/"><div class="lazyload-wrapper "><div style="height:2.5rem" class="lazyload-placeholder"></div></div></a></div><div class="ml-3"><p class="text-sm leading-5 font-medium text-gray-900"><a href="/author/david/" class="hover:underline">David Landup</a></p><div class="flex text-sm leading-5 text-gray-500"><time dateTime="2023-01-10">Jan 10, 2023</time><span class="mx-1">路</span><span>3<!-- --> min read</span></div></div></div></div></div></div><div><div class="flex flex-col rounded-lg shadow-lg overflow-hidden"><div class="flex-shrink-0"><a href="/bytes/java-8-collect-and-turn-stream-into-singleton-set/"><div class="lazyload-wrapper "><div style="height:12rem" class="lazyload-placeholder"></div></div></a></div><div class="flex-1 bg-white p-6 flex flex-col justify-between"><div class="flex-1"><p class="text-sm leading-5 font-medium text-primary">Byte</p><a class="block hover:no-underline" href="/bytes/java-8-collect-and-turn-stream-into-singleton-set/"><h3 class="mt-2 text-xl leading-7 font-semibold text-gray-900 hover:underline">Java 8 - Collect and Turn Stream into Singleton Set</h3><p class="mt-3 text-base leading-6 text-gray-500 break-words">In this short Byte - we&#x27;ll take a look at how you can collect and turn a list into a singleton set in Java, using the Functional API, and paired with the collectingAndThen() collector. Advice: If you&#x27;d like to read more about collectingAndThen() - read our in-depth &amp;quot;Guide to...</p></a></div><div class="mt-6 flex items-center"><div class="flex-shrink-0"><a href="/author/david/"><div class="lazyload-wrapper "><div style="height:2.5rem" class="lazyload-placeholder"></div></div></a></div><div class="ml-3"><p class="text-sm leading-5 font-medium text-gray-900"><a href="/author/david/" class="hover:underline">David Landup</a></p><div class="flex text-sm leading-5 text-gray-500"><time dateTime="2023-01-09">Jan 09, 2023</time><span class="mx-1">路</span><span>6<!-- --> min read</span></div></div></div></div></div></div><div><div class="flex flex-col rounded-lg shadow-lg overflow-hidden"><div class="flex-shrink-0"><a href="/bytes/java-8-collect-and-shuffle-list-or-stream/"><div class="lazyload-wrapper "><div style="height:12rem" class="lazyload-placeholder"></div></div></a></div><div class="flex-1 bg-white p-6 flex flex-col justify-between"><div class="flex-1"><p class="text-sm leading-5 font-medium text-primary">Byte</p><a class="block hover:no-underline" href="/bytes/java-8-collect-and-shuffle-list-or-stream/"><h3 class="mt-2 text-xl leading-7 font-semibold text-gray-900 hover:underline">Java 8 - Collect and Shuffle List or Stream</h3><p class="mt-3 text-base leading-6 text-gray-500 break-words">In this short Byte - we&#x27;ll take a look at how you can collect and shuffle a list in Java, using the Functional API, and paired with the collectingAndThen() collector. Advice: If you&#x27;d like to read more about collectingAndThen() - read our in-depth &amp;quot;Guide to Java 8 Collectors: collectingAndThen(...</p></a></div><div class="mt-6 flex items-center"><div class="flex-shrink-0"><a href="/author/david/"><div class="lazyload-wrapper "><div style="height:2.5rem" class="lazyload-placeholder"></div></div></a></div><div class="ml-3"><p class="text-sm leading-5 font-medium text-gray-900"><a href="/author/david/" class="hover:underline">David Landup</a></p><div class="flex text-sm leading-5 text-gray-500"><time dateTime="2023-01-06">Jan 06, 2023</time><span class="mx-1">路</span><span>4<!-- --> min read</span></div></div></div></div></div></div><div><div class="flex flex-col rounded-lg shadow-lg overflow-hidden"><div class="flex-shrink-0"><a href="/bytes/java-8-collect-and-slice-list-or-stream/"><div class="lazyload-wrapper "><div style="height:12rem" class="lazyload-placeholder"></div></div></a></div><div class="flex-1 bg-white p-6 flex flex-col justify-between"><div class="flex-1"><p class="text-sm leading-5 font-medium text-primary">Byte</p><a class="block hover:no-underline" href="/bytes/java-8-collect-and-slice-list-or-stream/"><h3 class="mt-2 text-xl leading-7 font-semibold text-gray-900 hover:underline">Java 8 - Collect and Slice List or Stream</h3><p class="mt-3 text-base leading-6 text-gray-500 break-words">In this short Byte - we&#x27;ll take a look at how you can collect and slice a list in Java, using the Functional API, and paired with the collectingAndThen() collector. Advice: If you&#x27;d like to read more about collectingAndThen() - read our in-depth &amp;quot;Guide to Java 8 Collectors: collectingAndThen(...</p></a></div><div class="mt-6 flex items-center"><div class="flex-shrink-0"><a href="/author/david/"><div class="lazyload-wrapper "><div style="height:2.5rem" class="lazyload-placeholder"></div></div></a></div><div class="ml-3"><p class="text-sm leading-5 font-medium text-gray-900"><a href="/author/david/" class="hover:underline">David Landup</a></p><div class="flex text-sm leading-5 text-gray-500"><time dateTime="2023-01-05">Jan 05, 2023</time><span class="mx-1">路</span><span>5<!-- --> min read</span></div></div></div></div></div></div><div><div class="flex flex-col rounded-lg shadow-lg overflow-hidden"><div class="flex-shrink-0"><a href="/bytes/java-get-number-of-elements-in-a-list/"><div class="lazyload-wrapper "><div style="height:12rem" class="lazyload-placeholder"></div></div></a></div><div class="flex-1 bg-white p-6 flex flex-col justify-between"><div class="flex-1"><p class="text-sm leading-5 font-medium text-primary">Byte</p><a class="block hover:no-underline" href="/bytes/java-get-number-of-elements-in-a-list/"><h3 class="mt-2 text-xl leading-7 font-semibold text-gray-900 hover:underline">Java: Get Number of Elements in a List</h3><p class="mt-3 text-base leading-6 text-gray-500 break-words">Getting the number of elements in a list is a common operation during software development. In Java - fetching the length of a list is done via the size() method, which accesses the cached length of the list in O(1) lookup time. List&amp;lt;Integer&amp;gt; arrayList = List.of(...</p></a></div><div class="mt-6 flex items-center"><div class="flex-shrink-0"><a href="/author/david/"><div class="lazyload-wrapper "><div style="height:2.5rem" class="lazyload-placeholder"></div></div></a></div><div class="ml-3"><p class="text-sm leading-5 font-medium text-gray-900"><a href="/author/david/" class="hover:underline">David Landup</a></p><div class="flex text-sm leading-5 text-gray-500"><time dateTime="2022-11-16">Nov 16, 2022</time><span class="mx-1">路</span><span>5<!-- --> min read</span></div></div></div></div></div></div></div><div class="mt-8 border-t border-gray-200 px-4 flex items-center justify-between sm:px-0"><div class="-mt-px w-0 flex-1 flex justify-end"><a class="border-t-2 border-transparent pt-4 pl-1 inline-flex items-center text-sm font-medium text-gray-500 hover:text-gray-700 hover:border-gray-300" href="/tag/java/page/2/">Next<svg class="ml-3 h-5 w-5 text-gray-400" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true"><path fill-rule="evenodd" d="M12.293 5.293a1 1 0 011.414 0l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414-1.414L14.586 11H3a1 1 0 110-2h11.586l-2.293-2.293a1 1 0 010-1.414z" clip-rule="evenodd"></path></svg></a></div></div></div></div></div></main><div class="bg-white border-t border-gray-300"><div class="max-w-screen-xl mx-auto pt-12 pb-6 px-4 sm:px-6 md:flex md:items-center md:justify-between lg:px-8"><div class="flex justify-center md:order-2"><a href="https://twitter.com/stackabuse" target="_blank" rel="noreferrer noopener" class="text-gray-500 hover:text-twitter"><span class="sr-only">Twitter</span><svg class="h-6 w-6" fill="currentColor" viewBox="0 0 24 24"><path d="M8.29 20.251c7.547 0 11.675-6.253 11.675-11.675 0-.178 0-.355-.012-.53A8.348 8.348 0 0022 5.92a8.19 8.19 0 01-2.357.646 4.118 4.118 0 001.804-2.27 8.224 8.224 0 01-2.605.996 4.107 4.107 0 00-6.993 3.743 11.65 11.65 0 01-8.457-4.287 4.106 4.106 0 001.27 5.477A4.072 4.072 0 012.8 9.713v.052a4.105 4.105 0 003.292 4.022 4.095 4.095 0 01-1.853.07 4.108 4.108 0 003.834 2.85A8.233 8.233 0 012 18.407a11.616 11.616 0 006.29 1.84"></path></svg></a><a href="https://github.com/stackabuse" target="_blank" rel="noreferrer noopener" class="ml-6 text-gray-500 hover:text-github"><span class="sr-only">GitHub</span><svg class="h-6 w-6" fill="currentColor" viewBox="0 0 24 24"><path fill-rule="evenodd" d="M12 2C6.477 2 2 6.484 2 12.017c0 4.425 2.865 8.18 6.839 9.504.5.092.682-.217.682-.483 0-.237-.008-.868-.013-1.703-2.782.605-3.369-1.343-3.369-1.343-.454-1.158-1.11-1.466-1.11-1.466-.908-.62.069-.608.069-.608 1.003.07 1.531 1.032 1.531 1.032.892 1.53 2.341 1.088 2.91.832.092-.647.35-1.088.636-1.338-2.22-.253-4.555-1.113-4.555-4.951 0-1.093.39-1.988 1.029-2.688-.103-.253-.446-1.272.098-2.65 0 0 .84-.27 2.75 1.026A9.564 9.564 0 0112 6.844c.85.004 1.705.115 2.504.337 1.909-1.296 2.747-1.027 2.747-1.027.546 1.379.202 2.398.1 2.651.64.7 1.028 1.595 1.028 2.688 0 3.848-2.339 4.695-4.566 4.943.359.309.678.92.678 1.855 0 1.338-.012 2.419-.012 2.747 0 .268.18.58.688.482A10.019 10.019 0 0022 12.017C22 6.484 17.522 2 12 2z" clip-rule="evenodd"></path></svg></a><a href="https://www.facebook.com/stackabuse" target="_blank" rel="noreferrer noopener" class="ml-6 text-gray-500 hover:text-facebook"><span class="sr-only">Facebook</span><svg class="h-6 w-6" fill="currentColor" viewBox="0 0 24 24"><path fill-rule="evenodd" d="M22 12c0-5.523-4.477-10-10-10S2 6.477 2 12c0 4.991 3.657 9.128 8.438 9.878v-6.987h-2.54V12h2.54V9.797c0-2.506 1.492-3.89 3.777-3.89 1.094 0 2.238.195 2.238.195v2.46h-1.26c-1.243 0-1.63.771-1.63 1.562V12h2.773l-.443 2.89h-2.33v6.988C18.343 21.128 22 16.991 22 12z" clip-rule="evenodd"></path></svg></a></div><div class="mt-8 md:mt-0 md:order-1"><p class="text-center text-base leading-6 text-gray-500">漏 2013-<!-- -->2024<!-- --> Stack Abuse. All rights reserved.</p><div class="text-sm"><a href="/about" class="pr-4 text-gray-500 border-r-2 border-grey-400 hover:no-underline hover:text-gray-600">About</a><a href="/disclosure" class="px-4 text-gray-500 border-r-2 border-grey-400 hover:no-underline hover:text-gray-600">Disclosure</a><a href="/privacy-policy" class="px-4 text-gray-500 border-r-2 border-grey-400 hover:no-underline hover:text-gray-600">Privacy</a><a href="/terms-of-service" class="pl-4 text-gray-500 hover:no-underline hover:text-gray-600">Terms</a><div id="ccpa" style="display:none;cursor:pointer">Do not share my Personal Information.</div></div></div></div></div></div></div><script id="__NEXT_DATA__" type="application/json">{"props":{"pageProps":{"tag":{"id":13,"name":"java","slug":"java","img_cover":null,"description_md":null,"description_html":"","visibility":"public","og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"color":null,"created_by":null,"updated_by":null,"created_at":1431358735000,"updated_at":1431358735000,"contents":[{"id":1831,"old_id":null,"uuid":"e81e6221-79d5-40e1-b73a-096752e89e2a","title":"How to List All Kafka Topics","slug":"how-to-list-all-kafka-topics","body_md":"If you've stumbled upon this article, chances are you've already been working with Apache Kafka, the open-source distributed streaming platform that has gained significant popularity for its ability to handle large-scale, real-time data processing. In this article, we'll dive into the nitty-gritty of managing and monitoring Kafka topics. Topics are the fundamental unit of Kafka's data organization and play a crucial role in its distributed architecture. We'll show you how to list all Kafka topics, both using the command-line tools provided by Kafka and programmatically through various APIs.\n\n## Prerequisites\n\nBefore we dive into the process of listing all Kafka topics, let's make sure you have everything set up and ready to go. Here's what you need to get started:\n\n### A Running Kafka Instance\n\nObviously you'll need a running instance of Apache Kafka to execute the commands and code examples in this article. If you don't already have Kafka installed and running on your system, don't worry, we've got you covered. You can download the latest version of Kafka from the official Apache Kafka website. After downloading, extract the archive and follow the \u003ca rel=\"nofollow noopener\" target=\"_blank\" href=\"https://kafka.apache.org/quickstart\"\u003equick start guide\u003c/a\u003e to get your Kafka instance up and running.\n\nOnce you've set up Kafka, start the Zookeeper and Kafka server with the following commands:\n\n```console\n# Start Zookeeper\n$ ./bin/zookeeper-server-start.sh ./config/zookeeper.properties\n\n# Start Kafka server\n$ ./bin/kafka-server-start.sh ./config/server.properties\n```\n\nMake sure your Zookeeper and Kafka server are running without any errors.\n\n:::note\n**Note**: It's important to note that this setup is suitable for local development and testing purposes. For a production environment, you should consider a more robust and secure configuration.\n:::\n\n### Access to Kafka's Command-Line Tools\n\nKafka comes with a set of handy command-line tools that make it easy to interact with the system. These tools are bundled with the Kafka installation and are typically located in the `bin` directory. Make sure that you have access to these tools and that they are in your system's `PATH`.\n\nNow that you have a running Kafka instance and access to the command-line tools, you're all set to start listing Kafka topics.\n\n## Using Command-Line Tools to List Topics\n\nTo list all Kafka topics, open your terminal and navigate to the bin directory of your Kafka installation. Execute the following command, making sure to replace `\u003cbroker-address\u003e` with the address of one of your Kafka brokers:\n\n```console\n$ ./kafka-topics.sh --list --bootstrap-server \u003cbroker-address\u003e\n```\n\nFor example, if your Kafka broker is running on `localhost:9092`, the command would be:\n\n```console\n$ ./kafka-topics.sh --list --bootstrap-server localhost:9092\n```\n\nThis command will display a list of all the topics in your Kafka instance. If you don't see any topics, it's likely that you haven't created any yet.\n\n:::note\n**Note**: Kafka brokers are responsible for managing and storing messages, and you need to provide the address of at least one broker to execute most Kafka commands. The `--bootstrap-server` parameter specifies the address of a broker that the command should connect to.\n:::\n\n### Troubleshooting Common Issues\n\nIf you encounter any issues while listing Kafka topics, here are a few common problems and their solutions:\n\n- _Error connecting to the broker_: Make sure your Kafka broker is running and that you've entered the correct broker address in the `--bootstrap-server` parameter.\n\n- _No topics listed_: If no topics are displayed, it's possible that there are no topics created in your Kafka instance. To create a topic, you can use the `kafka-topics.sh` script with the `--create` flag.\n\n- _Permission issues_: If you get a permission error while running the `kafka-topics.sh` script, make sure the script has the correct permissions. You may need to use `chmod +x kafka-topics.sh` to make it executable.\n\nThat's it! Now you can list all Kafka topics using the command-line tools. In the next section, we'll explore how to do this programmatically with Java and Python libraries.\n\n## Listing Topics Programmatically\n\nIn this section, we'll go beyond the command-line tools and explore how to list Kafka topics programmatically using the Kafka AdminClient API and some popular Python libraries.\n\n### Using Kafka AdminClient API\n\nThe Kafka AdminClient API allows you to interact with Kafka programmatically using Java. To list all topics, you can create an instance of the `AdminClient` class and call the `listTopics` method. Here's a code example to demonstrate this:\n\n```java\nimport org.apache.kafka.clients.admin.AdminClient;\nimport org.apache.kafka.clients.admin.AdminClientConfig;\nimport org.apache.kafka.clients.admin.ListTopicsResult;\n\nimport java.util.Properties;\nimport java.util.Set;\nimport java.util.concurrent.ExecutionException;\n\npublic class ListKafkaTopics {\n public static void main(String[] args) throws ExecutionException, InterruptedException {\n Properties properties = new Properties();\n properties.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, \"localhost:9092\");\n\n try (AdminClient adminClient = AdminClient.create(properties)) {\n ListTopicsResult topics = adminClient.listTopics();\n Set\u003cString\u003e topicNames = topics.names().get();\n\n System.out.println(\"Topics in the Kafka cluster:\");\n topicNames.forEach(System.out::println);\n }\n }\n}\n```\n\nReplace \"localhost:9092\" with your Kafka broker's address, and run the code. You'll see the list of topics printed in the console.\n\n### Utilizing Kafka Python Libraries\n\nThere are a couple of popular Python libraries you can use to interact with Kafka: \u003ca rel=\"nofollow noopener\" target=\"_blank\" href=\"https://github.com/confluentinc/confluent-kafka-python\"\u003econfluent-kafka-python\u003c/a\u003e and \u003ca rel=\"nofollow noopener\" target=\"_blank\" href=\"https://kafka-python.readthedocs.io/en/master/\"\u003ekafka-python\u003c/a\u003e. Let's see how to list topics using both of these libraries.\n\n1. Using `confluent-kafka-python`:\n\nFirst, install the `confluent-kafka-python` library if you haven't already:\n\n```console\n$ pip install confluent-kafka\n```\n\nNow, you can use the following code snippet to list all Kafka topics:\n\n```python\nfrom confluent_kafka.admin import AdminClient, NewTopic\n\nconf = {'bootstrap.servers': 'localhost:9092'}\nadmin_client = AdminClient(conf)\n\ntopic_list = admin_client.list_topics().topics\nprint(\"Topics in the Kafka cluster:\")\nfor topic in topic_list:\n print(topic)\n```\n\n2. Using `kafka-python`:\n\nInstall the `kafka-python` library with the following command:\n\n```console\n$ pip install kafka-python\n```\n\nAnd here's a code snippet that lists all Kafka topics using the `kafka-python` library:\n\n```python\nfrom kafka import KafkaAdminClient\n\nadmin_client = KafkaAdminClient(bootstrap_servers='localhost:9092')\ntopic_list = admin_client.list_topics()\n\nprint(\"Topics in the Kafka cluster:\")\nfor topic in topic_list:\n print(topic)\n```\n\nAnd that's it! Now you can not only list the topics from the command line, but programmatically as well.\n\n## Conclusion\n\nIn this article, we've explored various methods to list all Kafka topics, both using Kafka's command-line tools and programmatically with Java and Python libraries. \n\nI'd encourage you to dig deeper into other Kafka operations and explore more advanced features and use cases. It is a powerful tool that can cater to a wide range of data streaming needs, so don't hesitate to leverage it for your projects.\n\n\n","body_html":"\u003cp\u003eIf you've stumbled upon this article, chances are you've already been working with Apache Kafka, the open-source distributed streaming platform that has gained significant popularity for its ability to handle large-scale, real-time data processing. In this article, we'll dive into the nitty-gritty of managing and monitoring Kafka topics. Topics are the fundamental unit of Kafka's data organization and play a crucial role in its distributed architecture. We'll show you how to list all Kafka topics, both using the command-line tools provided by Kafka and programmatically through various APIs.\u003c/p\u003e\n\u003ch2 id=\"prerequisites\"\u003ePrerequisites\u003c/h2\u003e\n\u003cp\u003eBefore we dive into the process of listing all Kafka topics, let's make sure you have everything set up and ready to go. Here's what you need to get started:\u003c/p\u003e\n\u003ch3 id=\"arunningkafkainstance\"\u003eA Running Kafka Instance\u003c/h3\u003e\n\u003cp\u003eObviously you'll need a running instance of Apache Kafka to execute the commands and code examples in this article. If you don't already have Kafka installed and running on your system, don't worry, we've got you covered. You can download the latest version of Kafka from the official Apache Kafka website. After downloading, extract the archive and follow the \u003ca rel=\"nofollow noopener\" target=\"_blank\" href=\"https://kafka.apache.org/quickstart\"\u003equick start guide\u003c/a\u003e to get your Kafka instance up and running.\u003c/p\u003e\n\u003cp\u003eOnce you've set up Kafka, start the Zookeeper and Kafka server with the following commands:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-meta\"\u003e#\u003c/span\u003e\u003cspan class=\"bash\"\u003e Start Zookeeper\u003c/span\u003e\n\u003cspan class=\"hljs-meta\"\u003e$\u003c/span\u003e\u003cspan class=\"bash\"\u003e ./bin/zookeeper-server-start.sh ./config/zookeeper.properties\u003c/span\u003e\n\u003cspan class=\"hljs-meta\"\u003e\n#\u003c/span\u003e\u003cspan class=\"bash\"\u003e Start Kafka server\u003c/span\u003e\n\u003cspan class=\"hljs-meta\"\u003e$\u003c/span\u003e\u003cspan class=\"bash\"\u003e ./bin/kafka-server-start.sh ./config/server.properties\u003c/span\u003e\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eMake sure your Zookeeper and Kafka server are running without any errors.\u003c/p\u003e\n\n \u003cdiv class=\"alert alert-note\"\u003e\n \u003cdiv class=\"flex\"\u003e\n \n \u003cdiv class=\"flex-shrink-0 mr-3\"\u003e\n \u003cimg src=\"/assets/images/icon-information-circle-solid.svg\" class=\"icon\" aria-hidden=\"true\" /\u003e\n \u003c/div\u003e\n \n \u003cdiv class=\"w-full\"\u003e\n \u003cp\u003e\u003cstrong\u003eNote\u003c/strong\u003e: It's important to note that this setup is suitable for local development and testing purposes. For a production environment, you should consider a more robust and secure configuration.\u003c/p\u003e\n\n \u003c/div\u003e\n \u003c/div\u003e\n \u003c/div\u003e\n \u003ch3 id=\"accesstokafkascommandlinetools\"\u003eAccess to Kafka's Command-Line Tools\u003c/h3\u003e\n\u003cp\u003eKafka comes with a set of handy command-line tools that make it easy to interact with the system. These tools are bundled with the Kafka installation and are typically located in the \u003ccode\u003ebin\u003c/code\u003e directory. Make sure that you have access to these tools and that they are in your system's \u003ccode\u003ePATH\u003c/code\u003e.\u003c/p\u003e\n\u003cp\u003eNow that you have a running Kafka instance and access to the command-line tools, you're all set to start listing Kafka topics.\u003c/p\u003e\n\u003ch2 id=\"usingcommandlinetoolstolisttopics\"\u003eUsing Command-Line Tools to List Topics\u003c/h2\u003e\n\u003cp\u003eTo list all Kafka topics, open your terminal and navigate to the bin directory of your Kafka installation. Execute the following command, making sure to replace \u003ccode\u003e\u0026lt;broker-address\u0026gt;\u003c/code\u003e with the address of one of your Kafka brokers:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-meta\"\u003e$\u003c/span\u003e\u003cspan class=\"bash\"\u003e ./kafka-topics.sh --list --bootstrap-server \u0026lt;broker-address\u0026gt;\u003c/span\u003e\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eFor example, if your Kafka broker is running on \u003ccode\u003elocalhost:9092\u003c/code\u003e, the command would be:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-meta\"\u003e$\u003c/span\u003e\u003cspan class=\"bash\"\u003e ./kafka-topics.sh --list --bootstrap-server localhost:9092\u003c/span\u003e\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eThis command will display a list of all the topics in your Kafka instance. If you don't see any topics, it's likely that you haven't created any yet.\u003c/p\u003e\n\n \u003cdiv class=\"alert alert-note\"\u003e\n \u003cdiv class=\"flex\"\u003e\n \n \u003cdiv class=\"flex-shrink-0 mr-3\"\u003e\n \u003cimg src=\"/assets/images/icon-information-circle-solid.svg\" class=\"icon\" aria-hidden=\"true\" /\u003e\n \u003c/div\u003e\n \n \u003cdiv class=\"w-full\"\u003e\n \u003cp\u003e\u003cstrong\u003eNote\u003c/strong\u003e: Kafka brokers are responsible for managing and storing messages, and you need to provide the address of at least one broker to execute most Kafka commands. The \u003ccode\u003e--bootstrap-server\u003c/code\u003e parameter specifies the address of a broker that the command should connect to.\u003c/p\u003e\n\n \u003c/div\u003e\n \u003c/div\u003e\n \u003c/div\u003e\n \u003ch3 id=\"troubleshootingcommonissues\"\u003eTroubleshooting Common Issues\u003c/h3\u003e\n\u003cp\u003eIf you encounter any issues while listing Kafka topics, here are a few common problems and their solutions:\u003c/p\u003e\n\u003cul\u003e\n\u003cli\u003e\n\u003cp\u003e\u003cem\u003eError connecting to the broker\u003c/em\u003e: Make sure your Kafka broker is running and that you've entered the correct broker address in the \u003ccode\u003e--bootstrap-server\u003c/code\u003e parameter.\u003c/p\u003e\n\u003c/li\u003e\n\u003cli\u003e\n\u003cp\u003e\u003cem\u003eNo topics listed\u003c/em\u003e: If no topics are displayed, it's possible that there are no topics created in your Kafka instance. To create a topic, you can use the \u003ccode\u003ekafka-topics.sh\u003c/code\u003e script with the \u003ccode\u003e--create\u003c/code\u003e flag.\u003c/p\u003e\n\u003c/li\u003e\n\u003cli\u003e\n\u003cp\u003e\u003cem\u003ePermission issues\u003c/em\u003e: If you get a permission error while running the \u003ccode\u003ekafka-topics.sh\u003c/code\u003e script, make sure the script has the correct permissions. You may need to use \u003ccode\u003echmod +x kafka-topics.sh\u003c/code\u003e to make it executable.\u003c/p\u003e\n\u003c/li\u003e\n\u003c/ul\u003e\n\u003cp\u003eThat's it! Now you can list all Kafka topics using the command-line tools. In the next section, we'll explore how to do this programmatically with Java and Python libraries.\u003c/p\u003e\n\u003ch2 id=\"listingtopicsprogrammatically\"\u003eListing Topics Programmatically\u003c/h2\u003e\n\u003cp\u003eIn this section, we'll go beyond the command-line tools and explore how to list Kafka topics programmatically using the Kafka AdminClient API and some popular Python libraries.\u003c/p\u003e\n\u003ch3 id=\"usingkafkaadminclientapi\"\u003eUsing Kafka AdminClient API\u003c/h3\u003e\n\u003cp\u003eThe Kafka AdminClient API allows you to interact with Kafka programmatically using Java. To list all topics, you can create an instance of the \u003ccode\u003eAdminClient\u003c/code\u003e class and call the \u003ccode\u003elistTopics\u003c/code\u003e method. Here's a code example to demonstrate this:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-keyword\"\u003eimport\u003c/span\u003e org.apache.kafka.clients.admin.AdminClient;\n\u003cspan class=\"hljs-keyword\"\u003eimport\u003c/span\u003e org.apache.kafka.clients.admin.AdminClientConfig;\n\u003cspan class=\"hljs-keyword\"\u003eimport\u003c/span\u003e org.apache.kafka.clients.admin.ListTopicsResult;\n\n\u003cspan class=\"hljs-keyword\"\u003eimport\u003c/span\u003e java.util.Properties;\n\u003cspan class=\"hljs-keyword\"\u003eimport\u003c/span\u003e java.util.Set;\n\u003cspan class=\"hljs-keyword\"\u003eimport\u003c/span\u003e java.util.concurrent.ExecutionException;\n\n\u003cspan class=\"hljs-keyword\"\u003epublic\u003c/span\u003e \u003cspan class=\"hljs-class\"\u003e\u003cspan class=\"hljs-keyword\"\u003eclass\u003c/span\u003e \u003cspan class=\"hljs-title\"\u003eListKafkaTopics\u003c/span\u003e \u003c/span\u003e{\n \u003cspan class=\"hljs-function\"\u003e\u003cspan class=\"hljs-keyword\"\u003epublic\u003c/span\u003e \u003cspan class=\"hljs-keyword\"\u003estatic\u003c/span\u003e \u003cspan class=\"hljs-keyword\"\u003evoid\u003c/span\u003e \u003cspan class=\"hljs-title\"\u003emain\u003c/span\u003e\u003cspan class=\"hljs-params\"\u003e(String[] args)\u003c/span\u003e \u003cspan class=\"hljs-keyword\"\u003ethrows\u003c/span\u003e ExecutionException, InterruptedException \u003c/span\u003e{\n Properties properties = \u003cspan class=\"hljs-keyword\"\u003enew\u003c/span\u003e Properties();\n properties.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, \u003cspan class=\"hljs-string\"\u003e\u0026quot;localhost:9092\u0026quot;\u003c/span\u003e);\n\n \u003cspan class=\"hljs-keyword\"\u003etry\u003c/span\u003e (AdminClient adminClient = AdminClient.create(properties)) {\n ListTopicsResult topics = adminClient.listTopics();\n Set\u0026lt;String\u0026gt; topicNames = topics.names().get();\n\n System.out.println(\u003cspan class=\"hljs-string\"\u003e\u0026quot;Topics in the Kafka cluster:\u0026quot;\u003c/span\u003e);\n topicNames.forEach(System.out::println);\n }\n }\n}\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eReplace \u0026quot;localhost:9092\u0026quot; with your Kafka broker's address, and run the code. You'll see the list of topics printed in the console.\u003c/p\u003e\n\u003ch3 id=\"utilizingkafkapythonlibraries\"\u003eUtilizing Kafka Python Libraries\u003c/h3\u003e\n\u003cp\u003eThere are a couple of popular Python libraries you can use to interact with Kafka: \u003ca rel=\"nofollow noopener\" target=\"_blank\" href=\"https://github.com/confluentinc/confluent-kafka-python\"\u003econfluent-kafka-python\u003c/a\u003e and \u003ca rel=\"nofollow noopener\" target=\"_blank\" href=\"https://kafka-python.readthedocs.io/en/master/\"\u003ekafka-python\u003c/a\u003e. Let's see how to list topics using both of these libraries.\u003c/p\u003e\n\u003col\u003e\n\u003cli\u003eUsing \u003ccode\u003econfluent-kafka-python\u003c/code\u003e:\u003c/li\u003e\n\u003c/ol\u003e\n\u003cp\u003eFirst, install the \u003ccode\u003econfluent-kafka-python\u003c/code\u003e library if you haven't already:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-meta\"\u003e$\u003c/span\u003e\u003cspan class=\"bash\"\u003e pip install confluent-kafka\u003c/span\u003e\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eNow, you can use the following code snippet to list all Kafka topics:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-keyword\"\u003efrom\u003c/span\u003e confluent_kafka.admin \u003cspan class=\"hljs-keyword\"\u003eimport\u003c/span\u003e AdminClient, NewTopic\n\nconf = {\u003cspan class=\"hljs-string\"\u003e\u0026#x27;bootstrap.servers\u0026#x27;\u003c/span\u003e: \u003cspan class=\"hljs-string\"\u003e\u0026#x27;localhost:9092\u0026#x27;\u003c/span\u003e}\nadmin_client = AdminClient(conf)\n\ntopic_list = admin_client.list_topics().topics\n\u003cspan class=\"hljs-built_in\"\u003eprint\u003c/span\u003e(\u003cspan class=\"hljs-string\"\u003e\u0026quot;Topics in the Kafka cluster:\u0026quot;\u003c/span\u003e)\n\u003cspan class=\"hljs-keyword\"\u003efor\u003c/span\u003e topic \u003cspan class=\"hljs-keyword\"\u003ein\u003c/span\u003e topic_list:\n \u003cspan class=\"hljs-built_in\"\u003eprint\u003c/span\u003e(topic)\n\u003c/code\u003e\u003c/pre\u003e\n\u003col start=\"2\"\u003e\n\u003cli\u003eUsing \u003ccode\u003ekafka-python\u003c/code\u003e:\u003c/li\u003e\n\u003c/ol\u003e\n\u003cp\u003eInstall the \u003ccode\u003ekafka-python\u003c/code\u003e library with the following command:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-meta\"\u003e$\u003c/span\u003e\u003cspan class=\"bash\"\u003e pip install kafka-python\u003c/span\u003e\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eAnd here's a code snippet that lists all Kafka topics using the \u003ccode\u003ekafka-python\u003c/code\u003e library:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-keyword\"\u003efrom\u003c/span\u003e kafka \u003cspan class=\"hljs-keyword\"\u003eimport\u003c/span\u003e KafkaAdminClient\n\nadmin_client = KafkaAdminClient(bootstrap_servers=\u003cspan class=\"hljs-string\"\u003e\u0026#x27;localhost:9092\u0026#x27;\u003c/span\u003e)\ntopic_list = admin_client.list_topics()\n\n\u003cspan class=\"hljs-built_in\"\u003eprint\u003c/span\u003e(\u003cspan class=\"hljs-string\"\u003e\u0026quot;Topics in the Kafka cluster:\u0026quot;\u003c/span\u003e)\n\u003cspan class=\"hljs-keyword\"\u003efor\u003c/span\u003e topic \u003cspan class=\"hljs-keyword\"\u003ein\u003c/span\u003e topic_list:\n \u003cspan class=\"hljs-built_in\"\u003eprint\u003c/span\u003e(topic)\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eAnd that's it! Now you can not only list the topics from the command line, but programmatically as well.\u003c/p\u003e\n\u003ch2 id=\"conclusion\"\u003eConclusion\u003c/h2\u003e\n\u003cp\u003eIn this article, we've explored various methods to list all Kafka topics, both using Kafka's command-line tools and programmatically with Java and Python libraries.\u003c/p\u003e\n\u003cp\u003eI'd encourage you to dig deeper into other Kafka operations and explore more advanced features and use cases. It is a powerful tool that can cater to a wide range of data streaming needs, so don't hesitate to leverage it for your projects.\u003c/p\u003e\n","parent_id":null,"type":"article","status":"published","visibility":"public","img_feature":null,"is_featured":false,"locale":"en","custom_excerpt":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"comment_id":null,"og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":null,"read_time_min":8,"published_by":1,"published_at":1681939588175,"created_by":1,"updated_by":null,"created_at":1681939529738,"updated_at":1688312588431,"tags":[{"id":13,"name":"java","slug":"java","img_cover":null,"description_md":null,"description_html":"","visibility":"public","og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"color":null,"created_by":null,"updated_by":null,"created_at":1431358735000,"updated_at":1431358735000,"_pivot_content_id":1831,"_pivot_tag_id":13,"_pivot_sort_order":0},{"id":259,"name":"Kafka","slug":"kafka","img_cover":null,"description_md":"","description_html":"","visibility":"public","og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"color":null,"created_by":1,"updated_by":null,"created_at":1680896013172,"updated_at":1680896013172,"_pivot_content_id":1831,"_pivot_tag_id":259,"_pivot_sort_order":1}],"contributors":[{"id":1,"name":"Scott Robinson","slug":"scott","email":"scott@stackabuse.com","password_hash":"$2a$10$R8xoY2z9ZHj022/ShZIy8u0XtIC5RZMtw5QuUg7v6af3BvkPg2Pji","role_id":1,"img_profile":"//s3.stackabuse.com/media/users/1922fc67b9d11d6364dc01a3d19f4293.jpg","img_cover":null,"bio_md":null,"bio_html":"","website":null,"location":"Omaha, NE","facebook":null,"twitter":"ScottWRobinson","github":"scottwrobinson","status":"active","locale":null,"last_seen_at":1622236472000,"created_by":null,"updated_by":null,"created_at":1431311293000,"updated_at":1676411663329,"role":"owner","secret_token":"d07863ef29d9d376589f1d8fc82ffe8d","is_email_confirmed":true,"plan_name":"free","plan_interval":null,"sub_status":null,"referrer":null,"is_deleted":false,"_pivot_content_id":1831,"_pivot_user_id":1,"_pivot_role":"author","_pivot_sort_order":1}],"_pivot_tag_id":13,"_pivot_content_id":1831},{"id":1828,"old_id":null,"uuid":"ebcf4f63-2c7d-4361-8c0b-b7c6f8207f5f","title":"Purging Kafka Topics","slug":"purging-kafka-topics","body_md":"If you've been working with Kafka for a while, you're probably aware of the importance of properly managing your Kafka topics. As the backbone of your data streaming infrastructure, well-organized topics can keep your system running smoothly and efficiently, while ensuring that you're making the most out of the valuable data you're processing.\n\nPurging Kafka topics is an important part of managing your Kafka ecosystem. As data continues to flow through your system, you might find that old or unnecessary information starts to accumulate, taking up storage space and possibly even affecting the performance of your cluster.\n\n\u003e In this article, we'll discuss various techniques and strategies to purge Kafka topics, enabling you to maintain a lean and efficient data streaming infrastructure.\n\n## What are Kafka topics?\n\nAlright, before we get into purging Kafka topics, let's take a second to understand what they are exactly and why they play such a crucial role in the Kafka ecosystem.\n\nTopics are essentially categories or logical channels through which your data streams flow. Producers _write data records into topics_, and consumers _read from these topics_ in order to process the data. Topics are divided into partitions, which are ordered, immutable sequences of records. These partitions are distributed across multiple brokers in your cluster to ensure they're fault tolerant and highly available.\n\nHere's a simple example of creating a topic from the command line:\n\n```console\n$ kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 3 --topic my-sample-topic\n```\n\nThese topics have quite a few use-cases like real-time analytics, log aggregation, event sourcing, and message queuing. The idea is to separate and organize your data streams based on their purpose/category. For example, you might have separate topics for user logs, application metrics, and sales data. This separation makes it easier for consumers to process and analyze data based on their specific requirements.\n\n## Why purge Kafka topics?\n\nSo why should you even care about purging topics? The most obvious reason is storage. If our topics retain too many messages (and therefore storage), we could run into disk space issues and constrain the whole system.\n\nAnother reason to keep in mind is data retention policy compliance. Depending on your industry, you might have specific data retention policies that dictate how long you can store certain types of data. For example, GDPR, CCPA, and HIPAA require companies to manage, protect, and purge old data, among other requirements.\n\n## Methods to Purge Topics\n\nHere we'll explore various methods for purging Kafka topics. Each method has its own advantages and use cases, so let's take a closer look at each of them.\n\n### Changing Retention Settings\n\nOne way to purge a topic is by adjusting its log retention settings. You can control the retention by time or size. To modify the retention time for a topic, use the following command:\n\n```console\n$ kafka-configs.sh --zookeeper localhost:2181 --entity-type topics --entity-name my-example-topic --alter --add-config retention.ms=3600000\n```\n\nThis command sets the retention period for \"my-example-topic\" to 1 hour (i.e., 3600000 milliseconds). You can also set the retention size using `retention.bytes`. After making these changes, Kafka will automatically remove data that exceeds the specified retention settings.\n\n### Deleting the Topic\n\nIf you want to purge an entire topic, you can just delete it. Keep in mind that this will remove all data associated with the topic. To delete a Kafka topic, use the following command:\n\n```console\n$ kafka-topics.sh --zookeeper localhost:2181 --delete --topic my-example-topic\n```\n\nThis command deletes \"my-example-topic\" from your Kafka cluster.\n\n:::warn\n**Note:** For this to work, topic deletion must be enabled in the cluster by setting `delete.topic.enable=true` in the broker configuration.\n:::\n\n### Using Streams or KSQL for Data Filtering\n\nKafka Streams and KSQL are powerful tools that allow you to filter, transform, and process data within Kafka topics. You can use these tools to create new topics containing only the data you want to keep while discarding all other data. For example, using KSQL, you can create a new topic with filtered data like this:\n\n```sql\nCREATE STREAM filtered_stream AS\nSELECT *\nFROM original_stream\nWHERE \u003cyour_condition_here\u003e;\n```\n\nAfter creating the new topic with the filtered data, you can choose to delete the original topic if it's not needed anymore.\n\n### Compacting a Topic\n\nLog compaction is another method for purging Kafka topics. It removes older, obsolete records while retaining the latest value for each key. This method is particularly useful for topics with updating records, such as configuration or state data. To enable log compaction for a topic, set the `cleanup.policy` configuration to `compact`:\n\n```console\n$ kafka-configs.sh --zookeeper localhost:2181 --entity-type topics --entity-name my-example-topic --alter --add-config cleanup.policy=compact\n```\n\nAfter setting the new cleanup policy, Kafka will automatically compact the topic in the background, keeping only the most recent records for each key.\n\nEach of these methods has its own use cases and benefits, so it's essential to choose the one that best suits your requirements.\n\n## Best Practices\n\nNow that we've looked at a couple methods for purging Kafka topics, let's talk about some best practices to help you manage your topics effectively and efficiently.\n\n- **Frequently monitor topic storage usage**: Monitoring tools like Kafka's built-in JMX metrics, Confluent Control Center, or other third-party monitoring solutions can help you track storage usage and identify topics that may need purging. By keeping track of storage, you can proactively manage your Kafka cluster and avoid potential issues caused by storage constraints.\n\n- **Purge topics during low-traffic periods**: Purging topics can be resource-intensive, so it's a good idea to schedule these operations during periods of low traffic. When you perform purges when your cluster isn't as busy, you can reduce the impact on performance.\n\n- **Test purge methods in a dev or test environment**: Before applying any purge methods to your production Kafka cluster, test them in a non-production environment to make sure they work as expected. You can imagine that there are quite a few devs out there that wish they had done the same...\n\n## Conclusion\n\nIn this article we've covered a few methods for purging Kafka topics, including changing log retention settings, deleting topics, using Kafka Streams or KSQL for data filtering, and compacting topics. This gives you a few options to maintain an efficient and organized streaming infrastructure while reducing your storage usage and ensuring compliance with data retention policies.\n\nAs you manage your topics, don't forget to follow the best practices we've discussed! By following these guidelines, you can be sure to have a healthy cluster. If you have any feedback or tips, let us know in the comments!\n\n\n","body_html":"\u003cp\u003eIf you've been working with Kafka for a while, you're probably aware of the importance of properly managing your Kafka topics. As the backbone of your data streaming infrastructure, well-organized topics can keep your system running smoothly and efficiently, while ensuring that you're making the most out of the valuable data you're processing.\u003c/p\u003e\n\u003cp\u003ePurging Kafka topics is an important part of managing your Kafka ecosystem. As data continues to flow through your system, you might find that old or unnecessary information starts to accumulate, taking up storage space and possibly even affecting the performance of your cluster.\u003c/p\u003e\n\u003cblockquote\u003e\n\u003cp\u003eIn this article, we'll discuss various techniques and strategies to purge Kafka topics, enabling you to maintain a lean and efficient data streaming infrastructure.\u003c/p\u003e\n\u003c/blockquote\u003e\n\u003ch2 id=\"whatarekafkatopics\"\u003eWhat are Kafka topics?\u003c/h2\u003e\n\u003cp\u003eAlright, before we get into purging Kafka topics, let's take a second to understand what they are exactly and why they play such a crucial role in the Kafka ecosystem.\u003c/p\u003e\n\u003cp\u003eTopics are essentially categories or logical channels through which your data streams flow. Producers \u003cem\u003ewrite data records into topics\u003c/em\u003e, and consumers \u003cem\u003eread from these topics\u003c/em\u003e in order to process the data. Topics are divided into partitions, which are ordered, immutable sequences of records. These partitions are distributed across multiple brokers in your cluster to ensure they're fault tolerant and highly available.\u003c/p\u003e\n\u003cp\u003eHere's a simple example of creating a topic from the command line:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-meta\"\u003e$\u003c/span\u003e\u003cspan class=\"bash\"\u003e kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 3 --topic my-sample-topic\u003c/span\u003e\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eThese topics have quite a few use-cases like real-time analytics, log aggregation, event sourcing, and message queuing. The idea is to separate and organize your data streams based on their purpose/category. For example, you might have separate topics for user logs, application metrics, and sales data. This separation makes it easier for consumers to process and analyze data based on their specific requirements.\u003c/p\u003e\n\u003ch2 id=\"whypurgekafkatopics\"\u003eWhy purge Kafka topics?\u003c/h2\u003e\n\u003cp\u003eSo why should you even care about purging topics? The most obvious reason is storage. If our topics retain too many messages (and therefore storage), we could run into disk space issues and constrain the whole system.\u003c/p\u003e\n\u003cp\u003eAnother reason to keep in mind is data retention policy compliance. Depending on your industry, you might have specific data retention policies that dictate how long you can store certain types of data. For example, GDPR, CCPA, and HIPAA require companies to manage, protect, and purge old data, among other requirements.\u003c/p\u003e\n\u003ch2 id=\"methodstopurgetopics\"\u003eMethods to Purge Topics\u003c/h2\u003e\n\u003cp\u003eHere we'll explore various methods for purging Kafka topics. Each method has its own advantages and use cases, so let's take a closer look at each of them.\u003c/p\u003e\n\u003ch3 id=\"changingretentionsettings\"\u003eChanging Retention Settings\u003c/h3\u003e\n\u003cp\u003eOne way to purge a topic is by adjusting its log retention settings. You can control the retention by time or size. To modify the retention time for a topic, use the following command:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-meta\"\u003e$\u003c/span\u003e\u003cspan class=\"bash\"\u003e kafka-configs.sh --zookeeper localhost:2181 --entity-type topics --entity-name my-example-topic --alter --add-config retention.ms=3600000\u003c/span\u003e\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eThis command sets the retention period for \u0026quot;my-example-topic\u0026quot; to 1 hour (i.e., 3600000 milliseconds). You can also set the retention size using \u003ccode\u003eretention.bytes\u003c/code\u003e. After making these changes, Kafka will automatically remove data that exceeds the specified retention settings.\u003c/p\u003e\n\u003ch3 id=\"deletingthetopic\"\u003eDeleting the Topic\u003c/h3\u003e\n\u003cp\u003eIf you want to purge an entire topic, you can just delete it. Keep in mind that this will remove all data associated with the topic. To delete a Kafka topic, use the following command:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-meta\"\u003e$\u003c/span\u003e\u003cspan class=\"bash\"\u003e kafka-topics.sh --zookeeper localhost:2181 --delete --topic my-example-topic\u003c/span\u003e\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eThis command deletes \u0026quot;my-example-topic\u0026quot; from your Kafka cluster.\u003c/p\u003e\n\n \u003cdiv class=\"alert alert-warn\"\u003e\n \u003cdiv class=\"flex\"\u003e\n \n \u003cdiv class=\"flex-shrink-0 mr-3\"\u003e\n \u003cimg src=\"/assets/images/icon-exclamation-solid.svg\" class=\"icon\" aria-hidden=\"true\" /\u003e\n \u003c/div\u003e\n \n \u003cdiv class=\"w-full\"\u003e\n \u003cp\u003e\u003cstrong\u003eNote:\u003c/strong\u003e For this to work, topic deletion must be enabled in the cluster by setting \u003ccode\u003edelete.topic.enable=true\u003c/code\u003e in the broker configuration.\u003c/p\u003e\n\n \u003c/div\u003e\n \u003c/div\u003e\n \u003c/div\u003e\n \u003ch3 id=\"usingstreamsorksqlfordatafiltering\"\u003eUsing Streams or KSQL for Data Filtering\u003c/h3\u003e\n\u003cp\u003eKafka Streams and KSQL are powerful tools that allow you to filter, transform, and process data within Kafka topics. You can use these tools to create new topics containing only the data you want to keep while discarding all other data. For example, using KSQL, you can create a new topic with filtered data like this:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-keyword\"\u003eCREATE\u003c/span\u003e STREAM filtered_stream \u003cspan class=\"hljs-keyword\"\u003eAS\u003c/span\u003e\n\u003cspan class=\"hljs-keyword\"\u003eSELECT\u003c/span\u003e \u003cspan class=\"hljs-operator\"\u003e*\u003c/span\u003e\n\u003cspan class=\"hljs-keyword\"\u003eFROM\u003c/span\u003e original_stream\n\u003cspan class=\"hljs-keyword\"\u003eWHERE\u003c/span\u003e \u003cspan class=\"hljs-operator\"\u003e\u0026lt;\u003c/span\u003eyour_condition_here\u003cspan class=\"hljs-operator\"\u003e\u0026gt;\u003c/span\u003e;\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eAfter creating the new topic with the filtered data, you can choose to delete the original topic if it's not needed anymore.\u003c/p\u003e\n\u003ch3 id=\"compactingatopic\"\u003eCompacting a Topic\u003c/h3\u003e\n\u003cp\u003eLog compaction is another method for purging Kafka topics. It removes older, obsolete records while retaining the latest value for each key. This method is particularly useful for topics with updating records, such as configuration or state data. To enable log compaction for a topic, set the \u003ccode\u003ecleanup.policy\u003c/code\u003e configuration to \u003ccode\u003ecompact\u003c/code\u003e:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-meta\"\u003e$\u003c/span\u003e\u003cspan class=\"bash\"\u003e kafka-configs.sh --zookeeper localhost:2181 --entity-type topics --entity-name my-example-topic --alter --add-config cleanup.policy=compact\u003c/span\u003e\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eAfter setting the new cleanup policy, Kafka will automatically compact the topic in the background, keeping only the most recent records for each key.\u003c/p\u003e\n\u003cp\u003eEach of these methods has its own use cases and benefits, so it's essential to choose the one that best suits your requirements.\u003c/p\u003e\n\u003ch2 id=\"bestpractices\"\u003eBest Practices\u003c/h2\u003e\n\u003cp\u003eNow that we've looked at a couple methods for purging Kafka topics, let's talk about some best practices to help you manage your topics effectively and efficiently.\u003c/p\u003e\n\u003cul\u003e\n\u003cli\u003e\n\u003cp\u003e\u003cstrong\u003eFrequently monitor topic storage usage\u003c/strong\u003e: Monitoring tools like Kafka's built-in JMX metrics, Confluent Control Center, or other third-party monitoring solutions can help you track storage usage and identify topics that may need purging. By keeping track of storage, you can proactively manage your Kafka cluster and avoid potential issues caused by storage constraints.\u003c/p\u003e\n\u003c/li\u003e\n\u003cli\u003e\n\u003cp\u003e\u003cstrong\u003ePurge topics during low-traffic periods\u003c/strong\u003e: Purging topics can be resource-intensive, so it's a good idea to schedule these operations during periods of low traffic. When you perform purges when your cluster isn't as busy, you can reduce the impact on performance.\u003c/p\u003e\n\u003c/li\u003e\n\u003cli\u003e\n\u003cp\u003e\u003cstrong\u003eTest purge methods in a dev or test environment\u003c/strong\u003e: Before applying any purge methods to your production Kafka cluster, test them in a non-production environment to make sure they work as expected. You can imagine that there are quite a few devs out there that wish they had done the same...\u003c/p\u003e\n\u003c/li\u003e\n\u003c/ul\u003e\n\u003ch2 id=\"conclusion\"\u003eConclusion\u003c/h2\u003e\n\u003cp\u003eIn this article we've covered a few methods for purging Kafka topics, including changing log retention settings, deleting topics, using Kafka Streams or KSQL for data filtering, and compacting topics. This gives you a few options to maintain an efficient and organized streaming infrastructure while reducing your storage usage and ensuring compliance with data retention policies.\u003c/p\u003e\n\u003cp\u003eAs you manage your topics, don't forget to follow the best practices we've discussed! By following these guidelines, you can be sure to have a healthy cluster. If you have any feedback or tips, let us know in the comments!\u003c/p\u003e\n","parent_id":null,"type":"article","status":"published","visibility":"public","img_feature":null,"is_featured":false,"locale":"en","custom_excerpt":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"comment_id":null,"og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":null,"read_time_min":9,"published_by":1,"published_at":1681417087805,"created_by":1,"updated_by":null,"created_at":1681414224049,"updated_at":1687794238183,"tags":[{"id":13,"name":"java","slug":"java","img_cover":null,"description_md":null,"description_html":"","visibility":"public","og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"color":null,"created_by":null,"updated_by":null,"created_at":1431358735000,"updated_at":1431358735000,"_pivot_content_id":1828,"_pivot_tag_id":13,"_pivot_sort_order":1},{"id":259,"name":"Kafka","slug":"kafka","img_cover":null,"description_md":"","description_html":"","visibility":"public","og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"color":null,"created_by":1,"updated_by":null,"created_at":1680896013172,"updated_at":1680896013172,"_pivot_content_id":1828,"_pivot_tag_id":259,"_pivot_sort_order":0}],"contributors":[{"id":1,"name":"Scott Robinson","slug":"scott","email":"scott@stackabuse.com","password_hash":"$2a$10$R8xoY2z9ZHj022/ShZIy8u0XtIC5RZMtw5QuUg7v6af3BvkPg2Pji","role_id":1,"img_profile":"//s3.stackabuse.com/media/users/1922fc67b9d11d6364dc01a3d19f4293.jpg","img_cover":null,"bio_md":null,"bio_html":"","website":null,"location":"Omaha, NE","facebook":null,"twitter":"ScottWRobinson","github":"scottwrobinson","status":"active","locale":null,"last_seen_at":1622236472000,"created_by":null,"updated_by":null,"created_at":1431311293000,"updated_at":1676411663329,"role":"owner","secret_token":"d07863ef29d9d376589f1d8fc82ffe8d","is_email_confirmed":true,"plan_name":"free","plan_interval":null,"sub_status":null,"referrer":null,"is_deleted":false,"_pivot_content_id":1828,"_pivot_user_id":1,"_pivot_role":"author","_pivot_sort_order":1}],"_pivot_tag_id":13,"_pivot_content_id":1828},{"id":1745,"old_id":null,"uuid":"a10f9e01-3bfb-4136-b68f-b75cbe13deb5","title":"Java: Convert Int to a Byte","slug":"java-convert-int-to-a-byte","body_md":"In Java, an int is a 32-bit signed integer, while a byte is a 8-bit signed integer. Converting an int to a byte can be useful in certain situations, such as when working with binary data or when sending data over a network. In this article, we will explore different ways to convert an int to a byte in Java. We will first discuss the traditional method of using type casting and then look at the use of bit shifting / bit masking.\n\nNote that when converting from int to byte, the value of the int will be truncated to fit within the 8-bit range of a byte if the int is larger than that range. This can lead to data loss and should be taken into consideration when using these methods.\n\n## Casting Ints to Bytes\n\nOne of the simplest ways to convert an int to a byte in Java is to use type casting. Type casting is the process of converting one data type to another. In this case, we are converting an int to a byte. The syntax for type casting is to place the target data type in parentheses before the variable or value that needs to be converted.\n\nFor example, the following code converts the int variable `myInt` to a byte:\n\n```java\nint myInt = 128;\nbyte myByte = (byte) myInt;\n```\n\nIn this case, the value of `myInt` (128) is larger than the maximum value that can be stored in a byte (127), so the value will be truncated to fit in the 8-bit range. The resulting value of `myByte` will be -128.\n\nAnother way to convert int to byte is by using bit shifting and bit masking. Bit shifting is the process of moving the bits of a binary number to the left or right. Bit works by using a binary mask to extract or modify specific bits in a binary number. More specifically, this works by truncating the integer to the size of a byte.\n\nThe following code shows how to convert an int to a byte by using bit masking:\n\n```java\nint myInt = 128;\nbyte myByte = (byte) (myInt \u0026 0xff);\n```\n\nThis code first performs a bitwise AND operation between `myInt` and the hexadecimal value `0xff` (which is the equivalent to 255 in decimal). This sets all bits higher than the 8th bit to zero, effectively truncating the value of `myInt` to fit within the 8-bit range of a byte. Then, the result is casted to the byte type.\n\nThis method is a bit more explicit in how the conversion actually happens since you have more control over the truncation.\n\n## Using Conversion Helpers\n\nAnother way to convert an int to a byte (or vice versa) in Java is by using the `Byte` and `Integer` classes. The `Byte` class, for example, provides a static method called `toUnsignedInt` that can be used for the conversion, while the `Integer` class provides a method called `byteValue` that can be used to convert an int to a byte.\n\nFirst, let's see how to convert a byte to an integer, which we can achieve with `Byte.toUnsignedInt`. Here is an example:\n\n```java\nbyte myByte = -128;\nint myInt = Byte.toUnsignedInt(myByte);\n```\n\nIn this case, the value of `myByte` is -128, which is out of the range of the signed byte, but since the method `toUnsignedInt` is used, it will convert the byte to an unsigned int and the result will be 128.\n\nSimilarly, you can use the `Integer` class to convert an int to a byte. Here's an example of using the `Integer` class and its helper method to convert an int to a byte:\n\n```java\nInteger myInt = new Integer(200);\nbyte myByte = myInt.byteValue();\n```\n\nThe method `byteValue()` will convert the int to a byte. Similar to type casting, if the int is larger than the range of byte, the int will be truncated to fit within the 8-bit range of a byte.\n\nUsing the `Integer` class can be useful when working with integers and need to convert them to bytes in a more readable way, without the need of type casting or bit manipulation, which can be more prone to issues.\n\n## Conclusion\n\nIn summary, there are several ways to convert an int to a byte in Java, including using type casting, bit shifting and bit masking, and the `Integer` class method `byteValue()`. Each method has its own use cases and it's important to choose the right one based on the specific requirements of your project. For example, do you need a signed or unsigned conversion? In general, using the `Integer` class method `byteValue()` is more readable and less prone to error.\n\n","body_html":"\u003cp\u003eIn Java, an int is a 32-bit signed integer, while a byte is a 8-bit signed integer. Converting an int to a byte can be useful in certain situations, such as when working with binary data or when sending data over a network. In this article, we will explore different ways to convert an int to a byte in Java. We will first discuss the traditional method of using type casting and then look at the use of bit shifting / bit masking.\u003c/p\u003e\n\u003cp\u003eNote that when converting from int to byte, the value of the int will be truncated to fit within the 8-bit range of a byte if the int is larger than that range. This can lead to data loss and should be taken into consideration when using these methods.\u003c/p\u003e\n\u003ch2 id=\"castingintstobytes\"\u003eCasting Ints to Bytes\u003c/h2\u003e\n\u003cp\u003eOne of the simplest ways to convert an int to a byte in Java is to use type casting. Type casting is the process of converting one data type to another. In this case, we are converting an int to a byte. The syntax for type casting is to place the target data type in parentheses before the variable or value that needs to be converted.\u003c/p\u003e\n\u003cp\u003eFor example, the following code converts the int variable \u003ccode\u003emyInt\u003c/code\u003e to a byte:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-keyword\"\u003eint\u003c/span\u003e myInt = \u003cspan class=\"hljs-number\"\u003e128\u003c/span\u003e;\n\u003cspan class=\"hljs-keyword\"\u003ebyte\u003c/span\u003e myByte = (\u003cspan class=\"hljs-keyword\"\u003ebyte\u003c/span\u003e) myInt;\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eIn this case, the value of \u003ccode\u003emyInt\u003c/code\u003e (128) is larger than the maximum value that can be stored in a byte (127), so the value will be truncated to fit in the 8-bit range. The resulting value of \u003ccode\u003emyByte\u003c/code\u003e will be -128.\u003c/p\u003e\n\u003cp\u003eAnother way to convert int to byte is by using bit shifting and bit masking. Bit shifting is the process of moving the bits of a binary number to the left or right. Bit works by using a binary mask to extract or modify specific bits in a binary number. More specifically, this works by truncating the integer to the size of a byte.\u003c/p\u003e\n\u003cp\u003eThe following code shows how to convert an int to a byte by using bit masking:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-keyword\"\u003eint\u003c/span\u003e myInt = \u003cspan class=\"hljs-number\"\u003e128\u003c/span\u003e;\n\u003cspan class=\"hljs-keyword\"\u003ebyte\u003c/span\u003e myByte = (\u003cspan class=\"hljs-keyword\"\u003ebyte\u003c/span\u003e) (myInt \u0026amp; \u003cspan class=\"hljs-number\"\u003e0xff\u003c/span\u003e);\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eThis code first performs a bitwise AND operation between \u003ccode\u003emyInt\u003c/code\u003e and the hexadecimal value \u003ccode\u003e0xff\u003c/code\u003e (which is the equivalent to 255 in decimal). This sets all bits higher than the 8th bit to zero, effectively truncating the value of \u003ccode\u003emyInt\u003c/code\u003e to fit within the 8-bit range of a byte. Then, the result is casted to the byte type.\u003c/p\u003e\n\u003cp\u003eThis method is a bit more explicit in how the conversion actually happens since you have more control over the truncation.\u003c/p\u003e\n\u003ch2 id=\"usingconversionhelpers\"\u003eUsing Conversion Helpers\u003c/h2\u003e\n\u003cp\u003eAnother way to convert an int to a byte (or vice versa) in Java is by using the \u003ccode\u003eByte\u003c/code\u003e and \u003ccode\u003eInteger\u003c/code\u003e classes. The \u003ccode\u003eByte\u003c/code\u003e class, for example, provides a static method called \u003ccode\u003etoUnsignedInt\u003c/code\u003e that can be used for the conversion, while the \u003ccode\u003eInteger\u003c/code\u003e class provides a method called \u003ccode\u003ebyteValue\u003c/code\u003e that can be used to convert an int to a byte.\u003c/p\u003e\n\u003cp\u003eFirst, let's see how to convert a byte to an integer, which we can achieve with \u003ccode\u003eByte.toUnsignedInt\u003c/code\u003e. Here is an example:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-keyword\"\u003ebyte\u003c/span\u003e myByte = -\u003cspan class=\"hljs-number\"\u003e128\u003c/span\u003e;\n\u003cspan class=\"hljs-keyword\"\u003eint\u003c/span\u003e myInt = Byte.toUnsignedInt(myByte);\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eIn this case, the value of \u003ccode\u003emyByte\u003c/code\u003e is -128, which is out of the range of the signed byte, but since the method \u003ccode\u003etoUnsignedInt\u003c/code\u003e is used, it will convert the byte to an unsigned int and the result will be 128.\u003c/p\u003e\n\u003cp\u003eSimilarly, you can use the \u003ccode\u003eInteger\u003c/code\u003e class to convert an int to a byte. Here's an example of using the \u003ccode\u003eInteger\u003c/code\u003e class and its helper method to convert an int to a byte:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003eInteger myInt = \u003cspan class=\"hljs-keyword\"\u003enew\u003c/span\u003e Integer(\u003cspan class=\"hljs-number\"\u003e200\u003c/span\u003e);\n\u003cspan class=\"hljs-keyword\"\u003ebyte\u003c/span\u003e myByte = myInt.byteValue();\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eThe method \u003ccode\u003ebyteValue()\u003c/code\u003e will convert the int to a byte. Similar to type casting, if the int is larger than the range of byte, the int will be truncated to fit within the 8-bit range of a byte.\u003c/p\u003e\n\u003cp\u003eUsing the \u003ccode\u003eInteger\u003c/code\u003e class can be useful when working with integers and need to convert them to bytes in a more readable way, without the need of type casting or bit manipulation, which can be more prone to issues.\u003c/p\u003e\n\u003ch2 id=\"conclusion\"\u003eConclusion\u003c/h2\u003e\n\u003cp\u003eIn summary, there are several ways to convert an int to a byte in Java, including using type casting, bit shifting and bit masking, and the \u003ccode\u003eInteger\u003c/code\u003e class method \u003ccode\u003ebyteValue()\u003c/code\u003e. Each method has its own use cases and it's important to choose the right one based on the specific requirements of your project. For example, do you need a signed or unsigned conversion? In general, using the \u003ccode\u003eInteger\u003c/code\u003e class method \u003ccode\u003ebyteValue()\u003c/code\u003e is more readable and less prone to error.\u003c/p\u003e\n","parent_id":null,"type":"byte","status":"published","visibility":"public","img_feature":null,"is_featured":false,"locale":"en","custom_excerpt":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"comment_id":null,"og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":null,"read_time_min":12,"published_by":1,"published_at":1674576507756,"created_by":1,"updated_by":null,"created_at":1674576277335,"updated_at":1687450788638,"tags":[{"id":13,"name":"java","slug":"java","img_cover":null,"description_md":null,"description_html":"","visibility":"public","og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"color":null,"created_by":null,"updated_by":null,"created_at":1431358735000,"updated_at":1431358735000,"_pivot_content_id":1745,"_pivot_tag_id":13,"_pivot_sort_order":0}],"contributors":[{"id":1,"name":"Scott Robinson","slug":"scott","email":"scott@stackabuse.com","password_hash":"$2a$10$R8xoY2z9ZHj022/ShZIy8u0XtIC5RZMtw5QuUg7v6af3BvkPg2Pji","role_id":1,"img_profile":"//s3.stackabuse.com/media/users/1922fc67b9d11d6364dc01a3d19f4293.jpg","img_cover":null,"bio_md":null,"bio_html":"","website":null,"location":"Omaha, NE","facebook":null,"twitter":"ScottWRobinson","github":"scottwrobinson","status":"active","locale":null,"last_seen_at":1622236472000,"created_by":null,"updated_by":null,"created_at":1431311293000,"updated_at":1676411663329,"role":"owner","secret_token":"d07863ef29d9d376589f1d8fc82ffe8d","is_email_confirmed":true,"plan_name":"free","plan_interval":null,"sub_status":null,"referrer":null,"is_deleted":false,"_pivot_content_id":1745,"_pivot_user_id":1,"_pivot_role":"author","_pivot_sort_order":1}],"_pivot_tag_id":13,"_pivot_content_id":1745},{"id":1743,"old_id":null,"uuid":"9d44be43-56d6-4898-a3ca-454f92c9ecea","title":"Java Regular Expressions - Validate IP Addresses","slug":"java-regular-expressions-validate-ip-addresses","body_md":"## Check if IP Address is Valid Or Not with Java\n\nRegular Expressions are widely-applicable and used to match patterns in text, whether for search, validation or other processing.\n\nA common way to use them is to check whether *a number* is valid - i.e. follows a pattern. IP addresses follow a particular pattern, and can be tested with Regular Expressions.\n\nThis can also include validating Subnet masks, country-specific IPs, or any other criteria. In this example, we are just checking if a number is a valid IP or not:\n\n```java\npublic class RegexTutorial {\n public static void main(String[] args) {\n // Looking for a valid IP Address.\n Pattern pattern = Pattern.compile(\"^(([01]?\\\\d\\\\d?|2[0-4]\\\\d|25[0-5])\\\\.){3}([01]?\\\\d\\\\d?|2[0-4]\\\\d|25[0-5])$\");\n Matcher matcher = pattern.matcher(\"192.168.1.1\");\n boolean match = matcher.matches();\n System.out.println(match);\n }\n}\n```\n\nThe output will be:\n\n```java\ntrue\n```\n\nThis is a valid IP Address since this matches our criteria of 4 numbers separated by dots. All numbers are within the range of a valid IP Address too:\n\n```java\npublic class RegexTutorial {\n public static void main(String[] args) {\n // Looking for a valid IP Address.\n Pattern pattern = Pattern.compile(\"^(([01]?\\\\d\\\\d?|2[0-4]\\\\d|25[0-5])\\\\.){3}([01]?\\\\d\\\\d?|2[0-4]\\\\d|25[0-5])$\");\n Matcher matcher = pattern.matcher(\"400.168.1.1\");\n boolean match = matcher.matches();\n System.out.println(match);\n }\n}\n```\n\nThe output will be:\n\n```java\nfalse\n```\n\nThis is invalid since 400 is out of our IP Address range.","body_html":"\u003ch2 id=\"checkifipaddressisvalidornotwithjava\"\u003eCheck if IP Address is Valid Or Not with Java\u003c/h2\u003e\n\u003cp\u003eRegular Expressions are widely-applicable and used to match patterns in text, whether for search, validation or other processing.\u003c/p\u003e\n\u003cp\u003eA common way to use them is to check whether \u003cem\u003ea number\u003c/em\u003e is valid - i.e. follows a pattern. IP addresses follow a particular pattern, and can be tested with Regular Expressions.\u003c/p\u003e\n\u003cp\u003eThis can also include validating Subnet masks, country-specific IPs, or any other criteria. In this example, we are just checking if a number is a valid IP or not:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-keyword\"\u003epublic\u003c/span\u003e \u003cspan class=\"hljs-class\"\u003e\u003cspan class=\"hljs-keyword\"\u003eclass\u003c/span\u003e \u003cspan class=\"hljs-title\"\u003eRegexTutorial\u003c/span\u003e \u003c/span\u003e{\n \u003cspan class=\"hljs-function\"\u003e\u003cspan class=\"hljs-keyword\"\u003epublic\u003c/span\u003e \u003cspan class=\"hljs-keyword\"\u003estatic\u003c/span\u003e \u003cspan class=\"hljs-keyword\"\u003evoid\u003c/span\u003e \u003cspan class=\"hljs-title\"\u003emain\u003c/span\u003e\u003cspan class=\"hljs-params\"\u003e(String[] args)\u003c/span\u003e \u003c/span\u003e{\n \u003cspan class=\"hljs-comment\"\u003e// Looking for a valid IP Address.\u003c/span\u003e\n Pattern pattern = Pattern.compile(\u003cspan class=\"hljs-string\"\u003e\u0026quot;^(([01]?\\\\d\\\\d?|2[0-4]\\\\d|25[0-5])\\\\.){3}([01]?\\\\d\\\\d?|2[0-4]\\\\d|25[0-5])$\u0026quot;\u003c/span\u003e);\n Matcher matcher = pattern.matcher(\u003cspan class=\"hljs-string\"\u003e\u0026quot;192.168.1.1\u0026quot;\u003c/span\u003e);\n \u003cspan class=\"hljs-keyword\"\u003eboolean\u003c/span\u003e match = matcher.matches();\n System.out.println(match);\n }\n}\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eThe output will be:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-keyword\"\u003etrue\u003c/span\u003e\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eThis is a valid IP Address since this matches our criteria of 4 numbers separated by dots. All numbers are within the range of a valid IP Address too:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-keyword\"\u003epublic\u003c/span\u003e \u003cspan class=\"hljs-class\"\u003e\u003cspan class=\"hljs-keyword\"\u003eclass\u003c/span\u003e \u003cspan class=\"hljs-title\"\u003eRegexTutorial\u003c/span\u003e \u003c/span\u003e{\n \u003cspan class=\"hljs-function\"\u003e\u003cspan class=\"hljs-keyword\"\u003epublic\u003c/span\u003e \u003cspan class=\"hljs-keyword\"\u003estatic\u003c/span\u003e \u003cspan class=\"hljs-keyword\"\u003evoid\u003c/span\u003e \u003cspan class=\"hljs-title\"\u003emain\u003c/span\u003e\u003cspan class=\"hljs-params\"\u003e(String[] args)\u003c/span\u003e \u003c/span\u003e{\n \u003cspan class=\"hljs-comment\"\u003e// Looking for a valid IP Address.\u003c/span\u003e\n Pattern pattern = Pattern.compile(\u003cspan class=\"hljs-string\"\u003e\u0026quot;^(([01]?\\\\d\\\\d?|2[0-4]\\\\d|25[0-5])\\\\.){3}([01]?\\\\d\\\\d?|2[0-4]\\\\d|25[0-5])$\u0026quot;\u003c/span\u003e);\n Matcher matcher = pattern.matcher(\u003cspan class=\"hljs-string\"\u003e\u0026quot;400.168.1.1\u0026quot;\u003c/span\u003e);\n \u003cspan class=\"hljs-keyword\"\u003eboolean\u003c/span\u003e match = matcher.matches();\n System.out.println(match);\n }\n}\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eThe output will be:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-keyword\"\u003efalse\u003c/span\u003e\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eThis is invalid since 400 is out of our IP Address range.\u003c/p\u003e\n","parent_id":null,"type":"byte","status":"published","visibility":"public","img_feature":null,"is_featured":false,"locale":"en","custom_excerpt":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"comment_id":null,"og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":"In this short tutorial, learn how to check whether an input is a valid IP address or not in Java using Regular Expressions (RegEx).","read_time_min":4,"published_by":16,"published_at":1673407800000,"created_by":16,"updated_by":null,"created_at":1674230213849,"updated_at":1674230327654,"tags":[{"id":13,"name":"java","slug":"java","img_cover":null,"description_md":null,"description_html":"","visibility":"public","og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"color":null,"created_by":null,"updated_by":null,"created_at":1431358735000,"updated_at":1431358735000,"_pivot_content_id":1743,"_pivot_tag_id":13,"_pivot_sort_order":0}],"contributors":[{"id":9,"name":"Guest Contributor","slug":"guest","email":"scott+guest@stackabuse.com","password_hash":"$2a$10$vf2OQe7PrvOuq3yuklMPFOYVR80WHsZIsvn7murE5Farzh6CSc5au","role_id":4,"img_profile":"/assets/images/logo-sa-small.png","img_cover":null,"bio_md":null,"bio_html":"","website":null,"location":null,"facebook":null,"twitter":"@stackabuse","github":null,"status":"locked","locale":null,"last_seen_at":1516885731000,"created_by":null,"updated_by":null,"created_at":1516885655000,"updated_at":1629840514202,"role":"author","secret_token":"dd7f78d554ea508a4086470f131aed79","is_email_confirmed":true,"plan_name":"free","plan_interval":null,"sub_status":null,"referrer":null,"is_deleted":false,"_pivot_content_id":1743,"_pivot_user_id":9,"_pivot_role":"author","_pivot_sort_order":1},{"id":16,"name":"David Landup","slug":"david","email":"thealduinmaster@gmail.com","password_hash":"$2a$10$W/oMJdUBSTeG3trWAHa1xO0pQruxuLgD/6hS7VuxPafcmAxeBXmVi","role_id":2,"img_profile":"//s3.stackabuse.com/media/users/865cd7d217ea11c9d9555c4f666e2d73.jpg","img_cover":null,"bio_md":"Entrepreneur, Software and Machine Learning Engineer, with a deep fascination towards the application of Computation and Deep Learning in Life Sciences (Bioinformatics, Drug Discovery, Genomics), Neuroscience (Computational Neuroscience), robotics and BCIs. \n\nGreat passion for accessible education and promotion of reason, science, humanism, and progress.","bio_html":"\u003cp\u003eEntrepreneur, Software and Machine Learning Engineer, with a deep fascination towards the application of Computation and Deep Learning in Life Sciences (Bioinformatics, Drug Discovery, Genomics), Neuroscience (Computational Neuroscience), robotics and BCIs.\u003c/p\u003e\n\u003cp\u003eGreat passion for accessible education and promotion of reason, science, humanism, and progress.\u003c/p\u003e\n","website":"https://www.linkedin.com/in/david-landup-859455144/","location":"Serbia","facebook":"","twitter":"","github":null,"status":"inactive","locale":null,"last_seen_at":1622229427000,"created_by":null,"updated_by":1,"created_at":1534532687000,"updated_at":1692629560355,"role":"editor","secret_token":"2a2be92558fae38f89cfbd0c6a4ba90c","is_email_confirmed":true,"plan_name":"free","plan_interval":null,"sub_status":null,"referrer":null,"is_deleted":false,"_pivot_content_id":1743,"_pivot_user_id":16,"_pivot_role":"editor","_pivot_sort_order":0}],"_pivot_tag_id":13,"_pivot_content_id":1743},{"id":1742,"old_id":null,"uuid":"c307615c-f7e5-490f-80ce-145978e83fe5","title":"Java Regular Expressions - Validate SSN","slug":"java-regular-expressions-validate-ssn","body_md":"## Check if SSN is Valid Or Not with Java\n\nRegular Expressions are widely-applicable and used to match patterns in text, whether for search, validation or other processing.\n\nA common way to use them is to check whether *a number* is valid - i.e. follows a pattern. SSNs (Social Security Numbers) follow a particular pattern, and can be tested with Regular Expressions:\n\n```java\npublic class RegexTutorial {\n public static void main(String[] args) {\n // Looking for a valid SSN. \n // You can read more about the SSN rules here: https://www.ssa.gov/kc/SSAFactSheet--IssuingSSNs.pdf\n Pattern pattern = Pattern.compile(\"^(?!000|666)[0-8][0-9]{2}-(?!00)[0-9]{2}-(?!0000)[0-9]{4}$\");\n Matcher matcher = pattern.matcher(\"332-29-8932\");\n boolean match = matcher.matches();\n System.out.println(match);\n }\n}\n```\n\nThis number *follows the SSN format*:\n\n```java\ntrue\n```\n\nIt starts with 3 numbers, a dash, followed by 2 numbers, a dash, and then 4 numbers. Whether this SSN *exists* or not is a different debate, though.","body_html":"\u003ch2 id=\"checkifssnisvalidornotwithjava\"\u003eCheck if SSN is Valid Or Not with Java\u003c/h2\u003e\n\u003cp\u003eRegular Expressions are widely-applicable and used to match patterns in text, whether for search, validation or other processing.\u003c/p\u003e\n\u003cp\u003eA common way to use them is to check whether \u003cem\u003ea number\u003c/em\u003e is valid - i.e. follows a pattern. SSNs (Social Security Numbers) follow a particular pattern, and can be tested with Regular Expressions:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-keyword\"\u003epublic\u003c/span\u003e \u003cspan class=\"hljs-class\"\u003e\u003cspan class=\"hljs-keyword\"\u003eclass\u003c/span\u003e \u003cspan class=\"hljs-title\"\u003eRegexTutorial\u003c/span\u003e \u003c/span\u003e{\n \u003cspan class=\"hljs-function\"\u003e\u003cspan class=\"hljs-keyword\"\u003epublic\u003c/span\u003e \u003cspan class=\"hljs-keyword\"\u003estatic\u003c/span\u003e \u003cspan class=\"hljs-keyword\"\u003evoid\u003c/span\u003e \u003cspan class=\"hljs-title\"\u003emain\u003c/span\u003e\u003cspan class=\"hljs-params\"\u003e(String[] args)\u003c/span\u003e \u003c/span\u003e{\n \u003cspan class=\"hljs-comment\"\u003e// Looking for a valid SSN. \u003c/span\u003e\n \u003cspan class=\"hljs-comment\"\u003e// You can read more about the SSN rules here: https://www.ssa.gov/kc/SSAFactSheet--IssuingSSNs.pdf\u003c/span\u003e\n Pattern pattern = Pattern.compile(\u003cspan class=\"hljs-string\"\u003e\u0026quot;^(?!000|666)[0-8][0-9]{2}-(?!00)[0-9]{2}-(?!0000)[0-9]{4}$\u0026quot;\u003c/span\u003e);\n Matcher matcher = pattern.matcher(\u003cspan class=\"hljs-string\"\u003e\u0026quot;332-29-8932\u0026quot;\u003c/span\u003e);\n \u003cspan class=\"hljs-keyword\"\u003eboolean\u003c/span\u003e match = matcher.matches();\n System.out.println(match);\n }\n}\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eThis number \u003cem\u003efollows the SSN format\u003c/em\u003e:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-keyword\"\u003etrue\u003c/span\u003e\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eIt starts with 3 numbers, a dash, followed by 2 numbers, a dash, and then 4 numbers. Whether this SSN \u003cem\u003eexists\u003c/em\u003e or not is a different debate, though.\u003c/p\u003e\n","parent_id":null,"type":"byte","status":"published","visibility":"public","img_feature":null,"is_featured":false,"locale":"en","custom_excerpt":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"comment_id":null,"og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":"In this short tutorial, learn how to check whether an input number is a valid Social Security Number (SSN) or not.","read_time_min":3,"published_by":16,"published_at":1673321400000,"created_by":16,"updated_by":null,"created_at":1674228630558,"updated_at":1674229888196,"tags":[{"id":13,"name":"java","slug":"java","img_cover":null,"description_md":null,"description_html":"","visibility":"public","og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"color":null,"created_by":null,"updated_by":null,"created_at":1431358735000,"updated_at":1431358735000,"_pivot_content_id":1742,"_pivot_tag_id":13,"_pivot_sort_order":0}],"contributors":[{"id":16,"name":"David Landup","slug":"david","email":"thealduinmaster@gmail.com","password_hash":"$2a$10$W/oMJdUBSTeG3trWAHa1xO0pQruxuLgD/6hS7VuxPafcmAxeBXmVi","role_id":2,"img_profile":"//s3.stackabuse.com/media/users/865cd7d217ea11c9d9555c4f666e2d73.jpg","img_cover":null,"bio_md":"Entrepreneur, Software and Machine Learning Engineer, with a deep fascination towards the application of Computation and Deep Learning in Life Sciences (Bioinformatics, Drug Discovery, Genomics), Neuroscience (Computational Neuroscience), robotics and BCIs. \n\nGreat passion for accessible education and promotion of reason, science, humanism, and progress.","bio_html":"\u003cp\u003eEntrepreneur, Software and Machine Learning Engineer, with a deep fascination towards the application of Computation and Deep Learning in Life Sciences (Bioinformatics, Drug Discovery, Genomics), Neuroscience (Computational Neuroscience), robotics and BCIs.\u003c/p\u003e\n\u003cp\u003eGreat passion for accessible education and promotion of reason, science, humanism, and progress.\u003c/p\u003e\n","website":"https://www.linkedin.com/in/david-landup-859455144/","location":"Serbia","facebook":"","twitter":"","github":null,"status":"inactive","locale":null,"last_seen_at":1622229427000,"created_by":null,"updated_by":1,"created_at":1534532687000,"updated_at":1692629560355,"role":"editor","secret_token":"2a2be92558fae38f89cfbd0c6a4ba90c","is_email_confirmed":true,"plan_name":"free","plan_interval":null,"sub_status":null,"referrer":null,"is_deleted":false,"_pivot_content_id":1742,"_pivot_user_id":16,"_pivot_role":"author","_pivot_sort_order":0}],"_pivot_tag_id":13,"_pivot_content_id":1742},{"id":1737,"old_id":null,"uuid":"873f9ef9-c542-439a-959d-dc0457037f09","title":"Java 8 - Collect and Turn Stream into Singleton Set","slug":"java-8-collect-and-turn-stream-into-singleton-set","body_md":"In this short Byte - we'll take a look at how you can collect and turn a list into a singleton set in Java, using the Functional API, and paired with the `collectingAndThen()` collector.\n\n:::reference\n**Advice:** If you'd like to read more about `collectingAndThen()` - read our in-depth \u003ca target=\"_blank\" href=\"https://stackabuse.com/guide-to-java-8-collectors-collectingandthen/\"\u003e_\"Guide to Java 8 Collectors: collectingAndThen()\"!_\u003c/a\u003e\n:::\n\n### Turn a Stream into a Singleton Set\n\nWhen collecting a stream back into a list (streamed from a Java `Collection`) - you may decide to decide to return an immutable *singleton `Set`* that contains a single (and strictly single) immutable element.\n\nAn intuitive method to make use of here is `collectingAndThen()` which allows you to `collect()` a `Stream` and then run an anonymous function on the result:\n\n```java\npublic class Singleton {\n private final Stream\u003c?\u003e stream;\n \n public Set\u003c?\u003e getSingleton() {\n return stream.collect(\n collectingAndThen(\n toList(),\n l -\u003e {\n if (l.size() \u003e 1){\n throw new RuntimeException();\n } else{\n return l.isEmpty()\n ? emptySet()\n : singleton(l.get(0));\n }\n }\n )\n );\n }\n}\n```\n\nHere, we've collected the stream into a `List`, which is a *terminal operation* (ending the stream). Then, that list is streamed again, checking for the size. If the size is larger than 1 - a singleton `Set` cannot be created. In this example, we anticipate that the operation pipeline *before* the `collectingAndThen()` call, the stream is filtered of all elements but one.\n\nAfter the size check - we can create a new singleton `Set` with `singleton(l.get(0))` - passing the first (and only) element of the list into the `Collections.singleton()` method.\n\nYou can test the method and assert the correct output with:\n\n```java\n@Test\npublic void shouldCreateSingleton() {\n Singleton s1 = new Singleton(Stream.of(1,2));\n assertThrows(\n RuntimeException.class, \n () -\u003e s1.getSingleton()\n );\n \n Singleton s2 = new Singleton(Stream.empty());\n Set\u003c?\u003e singleton = s2.getSingleton();\n assertEquals(\"[]\", singleton.toString());\n \n Singleton s3 = new Singleton(Stream.of(1));\n singleton = s3.getSingleton();\n assertEquals(\"[1]\", singleton.toString());\n}\n```\n\n## Conclusion\n\nIn this short Byte - we took a look at how you can collect and turn a list into a singleton set in Java 8+.","body_html":"\u003cp\u003eIn this short Byte - we'll take a look at how you can collect and turn a list into a singleton set in Java, using the Functional API, and paired with the \u003ccode\u003ecollectingAndThen()\u003c/code\u003e collector.\u003c/p\u003e\n\n \u003cdiv class=\"alert alert-reference\"\u003e\n \u003cdiv class=\"flex\"\u003e\n \n \u003cdiv class=\"flex-shrink-0 mr-3\"\u003e\n \u003cimg src=\"/assets/images/icon-link-solid.svg\" class=\"icon\" aria-hidden=\"true\" /\u003e\n \u003c/div\u003e\n \n \u003cdiv class=\"w-full\"\u003e\n \u003cp\u003e\u003cstrong\u003eAdvice:\u003c/strong\u003e If you'd like to read more about \u003ccode\u003ecollectingAndThen()\u003c/code\u003e - read our in-depth \u003ca target=\"_blank\" href=\"https://stackabuse.com/guide-to-java-8-collectors-collectingandthen/\"\u003e\u003cem\u003e\u0026quot;Guide to Java 8 Collectors: collectingAndThen()\u0026quot;!\u003c/em\u003e\u003c/a\u003e\u003c/p\u003e\n\n \u003c/div\u003e\n \u003c/div\u003e\n \u003c/div\u003e\n \u003ch3 id=\"turnastreamintoasingletonset\"\u003eTurn a Stream into a Singleton Set\u003c/h3\u003e\n\u003cp\u003eWhen collecting a stream back into a list (streamed from a Java \u003ccode\u003eCollection\u003c/code\u003e) - you may decide to decide to return an immutable \u003cem\u003esingleton \u003ccode\u003eSet\u003c/code\u003e\u003c/em\u003e that contains a single (and strictly single) immutable element.\u003c/p\u003e\n\u003cp\u003eAn intuitive method to make use of here is \u003ccode\u003ecollectingAndThen()\u003c/code\u003e which allows you to \u003ccode\u003ecollect()\u003c/code\u003e a \u003ccode\u003eStream\u003c/code\u003e and then run an anonymous function on the result:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-keyword\"\u003epublic\u003c/span\u003e \u003cspan class=\"hljs-class\"\u003e\u003cspan class=\"hljs-keyword\"\u003eclass\u003c/span\u003e \u003cspan class=\"hljs-title\"\u003eSingleton\u003c/span\u003e \u003c/span\u003e{\n \u003cspan class=\"hljs-keyword\"\u003eprivate\u003c/span\u003e \u003cspan class=\"hljs-keyword\"\u003efinal\u003c/span\u003e Stream\u0026lt;?\u0026gt; stream;\n \n \u003cspan class=\"hljs-keyword\"\u003epublic\u003c/span\u003e Set\u0026lt;?\u0026gt; getSingleton() {\n \u003cspan class=\"hljs-keyword\"\u003ereturn\u003c/span\u003e stream.collect(\n collectingAndThen(\n toList(),\n l -\u0026gt; {\n \u003cspan class=\"hljs-keyword\"\u003eif\u003c/span\u003e (l.size() \u0026gt; \u003cspan class=\"hljs-number\"\u003e1\u003c/span\u003e){\n \u003cspan class=\"hljs-keyword\"\u003ethrow\u003c/span\u003e \u003cspan class=\"hljs-keyword\"\u003enew\u003c/span\u003e RuntimeException();\n } \u003cspan class=\"hljs-keyword\"\u003eelse\u003c/span\u003e{\n \u003cspan class=\"hljs-keyword\"\u003ereturn\u003c/span\u003e l.isEmpty()\n ? emptySet()\n : singleton(l.get(\u003cspan class=\"hljs-number\"\u003e0\u003c/span\u003e));\n }\n }\n )\n );\n }\n}\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eHere, we've collected the stream into a \u003ccode\u003eList\u003c/code\u003e, which is a \u003cem\u003eterminal operation\u003c/em\u003e (ending the stream). Then, that list is streamed again, checking for the size. If the size is larger than 1 - a singleton \u003ccode\u003eSet\u003c/code\u003e cannot be created. In this example, we anticipate that the operation pipeline \u003cem\u003ebefore\u003c/em\u003e the \u003ccode\u003ecollectingAndThen()\u003c/code\u003e call, the stream is filtered of all elements but one.\u003c/p\u003e\n\u003cp\u003eAfter the size check - we can create a new singleton \u003ccode\u003eSet\u003c/code\u003e with \u003ccode\u003esingleton(l.get(0))\u003c/code\u003e - passing the first (and only) element of the list into the \u003ccode\u003eCollections.singleton()\u003c/code\u003e method.\u003c/p\u003e\n\u003cp\u003eYou can test the method and assert the correct output with:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-meta\"\u003e@Test\u003c/span\u003e\n\u003cspan class=\"hljs-function\"\u003e\u003cspan class=\"hljs-keyword\"\u003epublic\u003c/span\u003e \u003cspan class=\"hljs-keyword\"\u003evoid\u003c/span\u003e \u003cspan class=\"hljs-title\"\u003eshouldCreateSingleton\u003c/span\u003e\u003cspan class=\"hljs-params\"\u003e()\u003c/span\u003e \u003c/span\u003e{\n Singleton s1 = \u003cspan class=\"hljs-keyword\"\u003enew\u003c/span\u003e Singleton(Stream.of(\u003cspan class=\"hljs-number\"\u003e1\u003c/span\u003e,\u003cspan class=\"hljs-number\"\u003e2\u003c/span\u003e));\n assertThrows(\n RuntimeException.class, \n () -\u0026gt; s1.getSingleton()\n );\n \n Singleton s2 = \u003cspan class=\"hljs-keyword\"\u003enew\u003c/span\u003e Singleton(Stream.empty());\n Set\u0026lt;?\u0026gt; singleton = s2.getSingleton();\n assertEquals(\u003cspan class=\"hljs-string\"\u003e\u0026quot;[]\u0026quot;\u003c/span\u003e, singleton.toString());\n \n Singleton s3 = \u003cspan class=\"hljs-keyword\"\u003enew\u003c/span\u003e Singleton(Stream.of(\u003cspan class=\"hljs-number\"\u003e1\u003c/span\u003e));\n singleton = s3.getSingleton();\n assertEquals(\u003cspan class=\"hljs-string\"\u003e\u0026quot;[1]\u0026quot;\u003c/span\u003e, singleton.toString());\n}\n\u003c/code\u003e\u003c/pre\u003e\n\u003ch2 id=\"conclusion\"\u003eConclusion\u003c/h2\u003e\n\u003cp\u003eIn this short Byte - we took a look at how you can collect and turn a list into a singleton set in Java 8+.\u003c/p\u003e\n","parent_id":null,"type":"byte","status":"published","visibility":"public","img_feature":null,"is_featured":false,"locale":"en","custom_excerpt":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"comment_id":null,"og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":"In this short Byte - learn how to collect and turn a list or stream into a singleton List in Java 8.","read_time_min":6,"published_by":16,"published_at":1673235000000,"created_by":16,"updated_by":null,"created_at":1674052188471,"updated_at":1674052327599,"tags":[{"id":13,"name":"java","slug":"java","img_cover":null,"description_md":null,"description_html":"","visibility":"public","og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"color":null,"created_by":null,"updated_by":null,"created_at":1431358735000,"updated_at":1431358735000,"_pivot_content_id":1737,"_pivot_tag_id":13,"_pivot_sort_order":0},{"id":150,"name":"streams","slug":"streams","img_cover":null,"description_md":null,"description_html":"","visibility":"public","og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"color":null,"created_by":null,"updated_by":null,"created_at":1572451232000,"updated_at":1572451232000,"_pivot_content_id":1737,"_pivot_tag_id":150,"_pivot_sort_order":1}],"contributors":[{"id":16,"name":"David Landup","slug":"david","email":"thealduinmaster@gmail.com","password_hash":"$2a$10$W/oMJdUBSTeG3trWAHa1xO0pQruxuLgD/6hS7VuxPafcmAxeBXmVi","role_id":2,"img_profile":"//s3.stackabuse.com/media/users/865cd7d217ea11c9d9555c4f666e2d73.jpg","img_cover":null,"bio_md":"Entrepreneur, Software and Machine Learning Engineer, with a deep fascination towards the application of Computation and Deep Learning in Life Sciences (Bioinformatics, Drug Discovery, Genomics), Neuroscience (Computational Neuroscience), robotics and BCIs. \n\nGreat passion for accessible education and promotion of reason, science, humanism, and progress.","bio_html":"\u003cp\u003eEntrepreneur, Software and Machine Learning Engineer, with a deep fascination towards the application of Computation and Deep Learning in Life Sciences (Bioinformatics, Drug Discovery, Genomics), Neuroscience (Computational Neuroscience), robotics and BCIs.\u003c/p\u003e\n\u003cp\u003eGreat passion for accessible education and promotion of reason, science, humanism, and progress.\u003c/p\u003e\n","website":"https://www.linkedin.com/in/david-landup-859455144/","location":"Serbia","facebook":"","twitter":"","github":null,"status":"inactive","locale":null,"last_seen_at":1622229427000,"created_by":null,"updated_by":1,"created_at":1534532687000,"updated_at":1692629560355,"role":"editor","secret_token":"2a2be92558fae38f89cfbd0c6a4ba90c","is_email_confirmed":true,"plan_name":"free","plan_interval":null,"sub_status":null,"referrer":null,"is_deleted":false,"_pivot_content_id":1737,"_pivot_user_id":16,"_pivot_role":"author","_pivot_sort_order":0},{"id":55,"name":"Hiram Kamau","slug":"hiram-k","email":"hiram.kamau@outlook.com","password_hash":"$2a$10$qX2.hlyJxd6h1TdcqlN8N.2SFKQmgM7hyoczst7UO48uAkNe.T.0u","role_id":4,"img_profile":"//s3.stackabuse.com/media/users/f38ed4ea2cc8a6b544f2db97e1e403f3.jpeg","img_cover":null,"bio_md":"In addition to catching code errors and going through debugging hell, I also obsess over whether writing in an active voice is truly better than doing it in passive.","bio_html":"\u003cp\u003eIn addition to catching code errors and going through debugging hell, I also obsess over whether writing in an active voice is truly better than doing it in passive.\u003c/p\u003e\n","website":"https://www.upwork.com/freelancers/~0157b88d591b73eb50","location":"Nairobi, Kenya","facebook":null,"twitter":"@hkamau_xight","github":"IdelsTak","status":"inactive","locale":null,"last_seen_at":1580967316000,"created_by":null,"updated_by":1,"created_at":1577973227000,"updated_at":1697580361272,"role":"author","secret_token":"39ccf3d9bc795193a5fcf10d11520090","is_email_confirmed":true,"plan_name":"free","plan_interval":null,"sub_status":null,"referrer":null,"is_deleted":false,"_pivot_content_id":1737,"_pivot_user_id":55,"_pivot_role":"author","_pivot_sort_order":1}],"_pivot_tag_id":13,"_pivot_content_id":1737},{"id":1736,"old_id":null,"uuid":"cb0d730f-6cd0-42cd-b7ae-39ad364b5656","title":"Java 8 - Collect and Shuffle List or Stream","slug":"java-8-collect-and-shuffle-list-or-stream","body_md":"In this short Byte - we'll take a look at how you can collect and shuffle a list in Java, using the Functional API, and paired with the `collectingAndThen()` collector.\n\n:::reference\n**Advice:** If you'd like to read more about `collectingAndThen()` - read our in-depth \u003ca target=\"_blank\" href=\"https://stackabuse.com/guide-to-java-8-collectors-collectingandthen/\"\u003e_\"Guide to Java 8 Collectors: collectingAndThen()\"!_\u003c/a\u003e\n:::\n\n### Collect and Shuffle a List in Java\n\nWhen collecting a stream back into a list (streamed from a Java `Collection`) - you may decide to shuffle it. Using Java 8's Functional API - working with streams is efficient and simple.\n\nAn intuitive method to make use of here is `collectingAndThen()` which allows you to `collect()` a `Stream` and then run an anonymous function on the result:\n\n```java\npublic class Shuffle {\n private final Stream\u003c?\u003e stream;\n \n public List\u003c?\u003e getList() {\n return stream.collect(\n collectingAndThen(\n toList(),\n l -\u003e {\n Collections.shuffle(l);\n return l;\n }\n )\n );\n } \n}\n```\n\nHere, we've collected the stream into a `List`, which is a *terminal operation* (ending the stream). Then, that list is streamed again, utilizing the central `Collections.shuffle()` method, which accepts any valid `Collection` and shuffles it in-place.\n\nYou can test the method and assert the correct output with:\n\n```java\n@Test\npublic void shouldShuffleList() {\n Shuffle shuffle = new Shuffle(Stream.of(1,2,3));\n List\u003c?\u003e list = shuffle.getList();\n \n assertNotEquals(\"[1, 2, 3]\", list.toString());\n}\n```\n\n## Conclusion\n\nIn this short Byte - we took a look at how you can collect and shuffle a list or stream in Java 8+.","body_html":"\u003cp\u003eIn this short Byte - we'll take a look at how you can collect and shuffle a list in Java, using the Functional API, and paired with the \u003ccode\u003ecollectingAndThen()\u003c/code\u003e collector.\u003c/p\u003e\n\n \u003cdiv class=\"alert alert-reference\"\u003e\n \u003cdiv class=\"flex\"\u003e\n \n \u003cdiv class=\"flex-shrink-0 mr-3\"\u003e\n \u003cimg src=\"/assets/images/icon-link-solid.svg\" class=\"icon\" aria-hidden=\"true\" /\u003e\n \u003c/div\u003e\n \n \u003cdiv class=\"w-full\"\u003e\n \u003cp\u003e\u003cstrong\u003eAdvice:\u003c/strong\u003e If you'd like to read more about \u003ccode\u003ecollectingAndThen()\u003c/code\u003e - read our in-depth \u003ca target=\"_blank\" href=\"https://stackabuse.com/guide-to-java-8-collectors-collectingandthen/\"\u003e\u003cem\u003e\u0026quot;Guide to Java 8 Collectors: collectingAndThen()\u0026quot;!\u003c/em\u003e\u003c/a\u003e\u003c/p\u003e\n\n \u003c/div\u003e\n \u003c/div\u003e\n \u003c/div\u003e\n \u003ch3 id=\"collectandshufflealistinjava\"\u003eCollect and Shuffle a List in Java\u003c/h3\u003e\n\u003cp\u003eWhen collecting a stream back into a list (streamed from a Java \u003ccode\u003eCollection\u003c/code\u003e) - you may decide to shuffle it. Using Java 8's Functional API - working with streams is efficient and simple.\u003c/p\u003e\n\u003cp\u003eAn intuitive method to make use of here is \u003ccode\u003ecollectingAndThen()\u003c/code\u003e which allows you to \u003ccode\u003ecollect()\u003c/code\u003e a \u003ccode\u003eStream\u003c/code\u003e and then run an anonymous function on the result:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-keyword\"\u003epublic\u003c/span\u003e \u003cspan class=\"hljs-class\"\u003e\u003cspan class=\"hljs-keyword\"\u003eclass\u003c/span\u003e \u003cspan class=\"hljs-title\"\u003eShuffle\u003c/span\u003e \u003c/span\u003e{\n \u003cspan class=\"hljs-keyword\"\u003eprivate\u003c/span\u003e \u003cspan class=\"hljs-keyword\"\u003efinal\u003c/span\u003e Stream\u0026lt;?\u0026gt; stream;\n \n \u003cspan class=\"hljs-keyword\"\u003epublic\u003c/span\u003e List\u0026lt;?\u0026gt; getList() {\n \u003cspan class=\"hljs-keyword\"\u003ereturn\u003c/span\u003e stream.collect(\n collectingAndThen(\n toList(),\n l -\u0026gt; {\n Collections.shuffle(l);\n \u003cspan class=\"hljs-keyword\"\u003ereturn\u003c/span\u003e l;\n }\n )\n );\n } \n}\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eHere, we've collected the stream into a \u003ccode\u003eList\u003c/code\u003e, which is a \u003cem\u003eterminal operation\u003c/em\u003e (ending the stream). Then, that list is streamed again, utilizing the central \u003ccode\u003eCollections.shuffle()\u003c/code\u003e method, which accepts any valid \u003ccode\u003eCollection\u003c/code\u003e and shuffles it in-place.\u003c/p\u003e\n\u003cp\u003eYou can test the method and assert the correct output with:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-meta\"\u003e@Test\u003c/span\u003e\n\u003cspan class=\"hljs-function\"\u003e\u003cspan class=\"hljs-keyword\"\u003epublic\u003c/span\u003e \u003cspan class=\"hljs-keyword\"\u003evoid\u003c/span\u003e \u003cspan class=\"hljs-title\"\u003eshouldShuffleList\u003c/span\u003e\u003cspan class=\"hljs-params\"\u003e()\u003c/span\u003e \u003c/span\u003e{\n Shuffle shuffle = \u003cspan class=\"hljs-keyword\"\u003enew\u003c/span\u003e Shuffle(Stream.of(\u003cspan class=\"hljs-number\"\u003e1\u003c/span\u003e,\u003cspan class=\"hljs-number\"\u003e2\u003c/span\u003e,\u003cspan class=\"hljs-number\"\u003e3\u003c/span\u003e));\n List\u0026lt;?\u0026gt; list = shuffle.getList();\n \n assertNotEquals(\u003cspan class=\"hljs-string\"\u003e\u0026quot;[1, 2, 3]\u0026quot;\u003c/span\u003e, list.toString());\n}\n\u003c/code\u003e\u003c/pre\u003e\n\u003ch2 id=\"conclusion\"\u003eConclusion\u003c/h2\u003e\n\u003cp\u003eIn this short Byte - we took a look at how you can collect and shuffle a list or stream in Java 8+.\u003c/p\u003e\n","parent_id":null,"type":"byte","status":"published","visibility":"public","img_feature":null,"is_featured":false,"locale":"en","custom_excerpt":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"comment_id":null,"og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":"In this short Byte - learn how to collect and shuffle a stream or list in Java 8.","read_time_min":4,"published_by":16,"published_at":1672975800000,"created_by":16,"updated_by":null,"created_at":1674052124556,"updated_at":1674052339137,"tags":[{"id":13,"name":"java","slug":"java","img_cover":null,"description_md":null,"description_html":"","visibility":"public","og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"color":null,"created_by":null,"updated_by":null,"created_at":1431358735000,"updated_at":1431358735000,"_pivot_content_id":1736,"_pivot_tag_id":13,"_pivot_sort_order":0},{"id":150,"name":"streams","slug":"streams","img_cover":null,"description_md":null,"description_html":"","visibility":"public","og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"color":null,"created_by":null,"updated_by":null,"created_at":1572451232000,"updated_at":1572451232000,"_pivot_content_id":1736,"_pivot_tag_id":150,"_pivot_sort_order":1}],"contributors":[{"id":16,"name":"David Landup","slug":"david","email":"thealduinmaster@gmail.com","password_hash":"$2a$10$W/oMJdUBSTeG3trWAHa1xO0pQruxuLgD/6hS7VuxPafcmAxeBXmVi","role_id":2,"img_profile":"//s3.stackabuse.com/media/users/865cd7d217ea11c9d9555c4f666e2d73.jpg","img_cover":null,"bio_md":"Entrepreneur, Software and Machine Learning Engineer, with a deep fascination towards the application of Computation and Deep Learning in Life Sciences (Bioinformatics, Drug Discovery, Genomics), Neuroscience (Computational Neuroscience), robotics and BCIs. \n\nGreat passion for accessible education and promotion of reason, science, humanism, and progress.","bio_html":"\u003cp\u003eEntrepreneur, Software and Machine Learning Engineer, with a deep fascination towards the application of Computation and Deep Learning in Life Sciences (Bioinformatics, Drug Discovery, Genomics), Neuroscience (Computational Neuroscience), robotics and BCIs.\u003c/p\u003e\n\u003cp\u003eGreat passion for accessible education and promotion of reason, science, humanism, and progress.\u003c/p\u003e\n","website":"https://www.linkedin.com/in/david-landup-859455144/","location":"Serbia","facebook":"","twitter":"","github":null,"status":"inactive","locale":null,"last_seen_at":1622229427000,"created_by":null,"updated_by":1,"created_at":1534532687000,"updated_at":1692629560355,"role":"editor","secret_token":"2a2be92558fae38f89cfbd0c6a4ba90c","is_email_confirmed":true,"plan_name":"free","plan_interval":null,"sub_status":null,"referrer":null,"is_deleted":false,"_pivot_content_id":1736,"_pivot_user_id":16,"_pivot_role":"author","_pivot_sort_order":0},{"id":55,"name":"Hiram Kamau","slug":"hiram-k","email":"hiram.kamau@outlook.com","password_hash":"$2a$10$qX2.hlyJxd6h1TdcqlN8N.2SFKQmgM7hyoczst7UO48uAkNe.T.0u","role_id":4,"img_profile":"//s3.stackabuse.com/media/users/f38ed4ea2cc8a6b544f2db97e1e403f3.jpeg","img_cover":null,"bio_md":"In addition to catching code errors and going through debugging hell, I also obsess over whether writing in an active voice is truly better than doing it in passive.","bio_html":"\u003cp\u003eIn addition to catching code errors and going through debugging hell, I also obsess over whether writing in an active voice is truly better than doing it in passive.\u003c/p\u003e\n","website":"https://www.upwork.com/freelancers/~0157b88d591b73eb50","location":"Nairobi, Kenya","facebook":null,"twitter":"@hkamau_xight","github":"IdelsTak","status":"inactive","locale":null,"last_seen_at":1580967316000,"created_by":null,"updated_by":1,"created_at":1577973227000,"updated_at":1697580361272,"role":"author","secret_token":"39ccf3d9bc795193a5fcf10d11520090","is_email_confirmed":true,"plan_name":"free","plan_interval":null,"sub_status":null,"referrer":null,"is_deleted":false,"_pivot_content_id":1736,"_pivot_user_id":55,"_pivot_role":"author","_pivot_sort_order":1}],"_pivot_tag_id":13,"_pivot_content_id":1736},{"id":1735,"old_id":null,"uuid":"118524b6-c3f4-45ef-ac66-82c491ede5a5","title":"Java 8 - Collect and Slice List or Stream","slug":"java-8-collect-and-slice-list-or-stream","body_md":"In this short Byte - we'll take a look at how you can collect and slice a list in Java, using the Functional API, and paired with the `collectingAndThen()` collector.\n\n:::reference\n**Advice:** If you'd like to read more about `collectingAndThen()` - read our in-depth \u003ca target=\"_blank\" href=\"https://stackabuse.com/guide-to-java-8-collectors-collectingandthen/\"\u003e_\"Guide to Java 8 Collectors: collectingAndThen()\"!_\u003c/a\u003e\n:::\n\n### Slice a List in Java\n\nWhen collecting a stream back into a list (streamed from a Java `Collection`) - you may decide to slice it, given some start and end, effectively returning a sublist of the original one. Using Java 8's Functional API - working with streams is efficient and simple.\n\nAn intuitive method to make use of here is `collectingAndThen()` which allows you to `collect()` a `Stream` and then run an anonymous function on the result:\n\n```java\npublic class Slice {\n private final Stream\u003cInteger\u003e s;\n private final int from;\n private final int to;\n \n public List\u003cInteger\u003e getList() {\n return s.collect(\n Collectors.collectingAndThen(\n toList(),\n l -\u003e {\n return l.stream()\n .skip(from)\n .limit(to - (from - 1))\n .collect(toList());\n }\n )\n );\n }\n}\n```\n\nHere, we've collected the stream into a `List`, which is a *terminal operation* (ending the stream). Then, that list is streamed again, utilizing `skip()` and `limit()` to sublist the original list, collecting back into a `List`.\n\nYou can test the method and assert the correct output with:\n\n```java\n@Test\npublic void shouldSliceList() {\n Stream\u003cInteger\u003e stream = IntStream\n .rangeClosed(0, 10)\n .boxed();\n Slice slice = new Slice(stream, 3, 7);\n List\u003cInteger\u003e list = slice.getList();\n \n assertEquals(\n \"[3, 4, 5, 6, 7]\",\n list.toString()\n );\n}\n```\n\n## Conclusion\n\nIn this short Byte - we took a look at how you can collect and slice a list in Java 8+.","body_html":"\u003cp\u003eIn this short Byte - we'll take a look at how you can collect and slice a list in Java, using the Functional API, and paired with the \u003ccode\u003ecollectingAndThen()\u003c/code\u003e collector.\u003c/p\u003e\n\n \u003cdiv class=\"alert alert-reference\"\u003e\n \u003cdiv class=\"flex\"\u003e\n \n \u003cdiv class=\"flex-shrink-0 mr-3\"\u003e\n \u003cimg src=\"/assets/images/icon-link-solid.svg\" class=\"icon\" aria-hidden=\"true\" /\u003e\n \u003c/div\u003e\n \n \u003cdiv class=\"w-full\"\u003e\n \u003cp\u003e\u003cstrong\u003eAdvice:\u003c/strong\u003e If you'd like to read more about \u003ccode\u003ecollectingAndThen()\u003c/code\u003e - read our in-depth \u003ca target=\"_blank\" href=\"https://stackabuse.com/guide-to-java-8-collectors-collectingandthen/\"\u003e\u003cem\u003e\u0026quot;Guide to Java 8 Collectors: collectingAndThen()\u0026quot;!\u003c/em\u003e\u003c/a\u003e\u003c/p\u003e\n\n \u003c/div\u003e\n \u003c/div\u003e\n \u003c/div\u003e\n \u003ch3 id=\"slicealistinjava\"\u003eSlice a List in Java\u003c/h3\u003e\n\u003cp\u003eWhen collecting a stream back into a list (streamed from a Java \u003ccode\u003eCollection\u003c/code\u003e) - you may decide to slice it, given some start and end, effectively returning a sublist of the original one. Using Java 8's Functional API - working with streams is efficient and simple.\u003c/p\u003e\n\u003cp\u003eAn intuitive method to make use of here is \u003ccode\u003ecollectingAndThen()\u003c/code\u003e which allows you to \u003ccode\u003ecollect()\u003c/code\u003e a \u003ccode\u003eStream\u003c/code\u003e and then run an anonymous function on the result:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-keyword\"\u003epublic\u003c/span\u003e \u003cspan class=\"hljs-class\"\u003e\u003cspan class=\"hljs-keyword\"\u003eclass\u003c/span\u003e \u003cspan class=\"hljs-title\"\u003eSlice\u003c/span\u003e \u003c/span\u003e{\n \u003cspan class=\"hljs-keyword\"\u003eprivate\u003c/span\u003e \u003cspan class=\"hljs-keyword\"\u003efinal\u003c/span\u003e Stream\u0026lt;Integer\u0026gt; s;\n \u003cspan class=\"hljs-keyword\"\u003eprivate\u003c/span\u003e \u003cspan class=\"hljs-keyword\"\u003efinal\u003c/span\u003e \u003cspan class=\"hljs-keyword\"\u003eint\u003c/span\u003e from;\n \u003cspan class=\"hljs-keyword\"\u003eprivate\u003c/span\u003e \u003cspan class=\"hljs-keyword\"\u003efinal\u003c/span\u003e \u003cspan class=\"hljs-keyword\"\u003eint\u003c/span\u003e to;\n \n \u003cspan class=\"hljs-function\"\u003e\u003cspan class=\"hljs-keyword\"\u003epublic\u003c/span\u003e List\u0026lt;Integer\u0026gt; \u003cspan class=\"hljs-title\"\u003egetList\u003c/span\u003e\u003cspan class=\"hljs-params\"\u003e()\u003c/span\u003e \u003c/span\u003e{\n \u003cspan class=\"hljs-keyword\"\u003ereturn\u003c/span\u003e s.collect(\n Collectors.collectingAndThen(\n toList(),\n l -\u0026gt; {\n \u003cspan class=\"hljs-keyword\"\u003ereturn\u003c/span\u003e l.stream()\n .skip(from)\n .limit(to - (from - \u003cspan class=\"hljs-number\"\u003e1\u003c/span\u003e))\n .collect(toList());\n }\n )\n );\n }\n}\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eHere, we've collected the stream into a \u003ccode\u003eList\u003c/code\u003e, which is a \u003cem\u003eterminal operation\u003c/em\u003e (ending the stream). Then, that list is streamed again, utilizing \u003ccode\u003eskip()\u003c/code\u003e and \u003ccode\u003elimit()\u003c/code\u003e to sublist the original list, collecting back into a \u003ccode\u003eList\u003c/code\u003e.\u003c/p\u003e\n\u003cp\u003eYou can test the method and assert the correct output with:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003e\u003cspan class=\"hljs-meta\"\u003e@Test\u003c/span\u003e\n\u003cspan class=\"hljs-function\"\u003e\u003cspan class=\"hljs-keyword\"\u003epublic\u003c/span\u003e \u003cspan class=\"hljs-keyword\"\u003evoid\u003c/span\u003e \u003cspan class=\"hljs-title\"\u003eshouldSliceList\u003c/span\u003e\u003cspan class=\"hljs-params\"\u003e()\u003c/span\u003e \u003c/span\u003e{\n Stream\u0026lt;Integer\u0026gt; stream = IntStream\n .rangeClosed(\u003cspan class=\"hljs-number\"\u003e0\u003c/span\u003e, \u003cspan class=\"hljs-number\"\u003e10\u003c/span\u003e)\n .boxed();\n Slice slice = \u003cspan class=\"hljs-keyword\"\u003enew\u003c/span\u003e Slice(stream, \u003cspan class=\"hljs-number\"\u003e3\u003c/span\u003e, \u003cspan class=\"hljs-number\"\u003e7\u003c/span\u003e);\n List\u0026lt;Integer\u0026gt; list = slice.getList();\n \n assertEquals(\n \u003cspan class=\"hljs-string\"\u003e\u0026quot;[3, 4, 5, 6, 7]\u0026quot;\u003c/span\u003e,\n list.toString()\n );\n}\n\u003c/code\u003e\u003c/pre\u003e\n\u003ch2 id=\"conclusion\"\u003eConclusion\u003c/h2\u003e\n\u003cp\u003eIn this short Byte - we took a look at how you can collect and slice a list in Java 8+.\u003c/p\u003e\n","parent_id":null,"type":"byte","status":"published","visibility":"public","img_feature":null,"is_featured":false,"locale":"en","custom_excerpt":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"comment_id":null,"og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":"In this short Byte - learn how to collect and slice a stream or list, given a range, in Java 8.","read_time_min":5,"published_by":16,"published_at":1672889400000,"created_by":16,"updated_by":null,"created_at":1674050552472,"updated_at":1674052090617,"tags":[{"id":13,"name":"java","slug":"java","img_cover":null,"description_md":null,"description_html":"","visibility":"public","og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"color":null,"created_by":null,"updated_by":null,"created_at":1431358735000,"updated_at":1431358735000,"_pivot_content_id":1735,"_pivot_tag_id":13,"_pivot_sort_order":0},{"id":150,"name":"streams","slug":"streams","img_cover":null,"description_md":null,"description_html":"","visibility":"public","og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"color":null,"created_by":null,"updated_by":null,"created_at":1572451232000,"updated_at":1572451232000,"_pivot_content_id":1735,"_pivot_tag_id":150,"_pivot_sort_order":1}],"contributors":[{"id":16,"name":"David Landup","slug":"david","email":"thealduinmaster@gmail.com","password_hash":"$2a$10$W/oMJdUBSTeG3trWAHa1xO0pQruxuLgD/6hS7VuxPafcmAxeBXmVi","role_id":2,"img_profile":"//s3.stackabuse.com/media/users/865cd7d217ea11c9d9555c4f666e2d73.jpg","img_cover":null,"bio_md":"Entrepreneur, Software and Machine Learning Engineer, with a deep fascination towards the application of Computation and Deep Learning in Life Sciences (Bioinformatics, Drug Discovery, Genomics), Neuroscience (Computational Neuroscience), robotics and BCIs. \n\nGreat passion for accessible education and promotion of reason, science, humanism, and progress.","bio_html":"\u003cp\u003eEntrepreneur, Software and Machine Learning Engineer, with a deep fascination towards the application of Computation and Deep Learning in Life Sciences (Bioinformatics, Drug Discovery, Genomics), Neuroscience (Computational Neuroscience), robotics and BCIs.\u003c/p\u003e\n\u003cp\u003eGreat passion for accessible education and promotion of reason, science, humanism, and progress.\u003c/p\u003e\n","website":"https://www.linkedin.com/in/david-landup-859455144/","location":"Serbia","facebook":"","twitter":"","github":null,"status":"inactive","locale":null,"last_seen_at":1622229427000,"created_by":null,"updated_by":1,"created_at":1534532687000,"updated_at":1692629560355,"role":"editor","secret_token":"2a2be92558fae38f89cfbd0c6a4ba90c","is_email_confirmed":true,"plan_name":"free","plan_interval":null,"sub_status":null,"referrer":null,"is_deleted":false,"_pivot_content_id":1735,"_pivot_user_id":16,"_pivot_role":"author","_pivot_sort_order":0},{"id":55,"name":"Hiram Kamau","slug":"hiram-k","email":"hiram.kamau@outlook.com","password_hash":"$2a$10$qX2.hlyJxd6h1TdcqlN8N.2SFKQmgM7hyoczst7UO48uAkNe.T.0u","role_id":4,"img_profile":"//s3.stackabuse.com/media/users/f38ed4ea2cc8a6b544f2db97e1e403f3.jpeg","img_cover":null,"bio_md":"In addition to catching code errors and going through debugging hell, I also obsess over whether writing in an active voice is truly better than doing it in passive.","bio_html":"\u003cp\u003eIn addition to catching code errors and going through debugging hell, I also obsess over whether writing in an active voice is truly better than doing it in passive.\u003c/p\u003e\n","website":"https://www.upwork.com/freelancers/~0157b88d591b73eb50","location":"Nairobi, Kenya","facebook":null,"twitter":"@hkamau_xight","github":"IdelsTak","status":"inactive","locale":null,"last_seen_at":1580967316000,"created_by":null,"updated_by":1,"created_at":1577973227000,"updated_at":1697580361272,"role":"author","secret_token":"39ccf3d9bc795193a5fcf10d11520090","is_email_confirmed":true,"plan_name":"free","plan_interval":null,"sub_status":null,"referrer":null,"is_deleted":false,"_pivot_content_id":1735,"_pivot_user_id":55,"_pivot_role":"author","_pivot_sort_order":1}],"_pivot_tag_id":13,"_pivot_content_id":1735},{"id":1690,"old_id":null,"uuid":"1df75af0-da25-4b1d-93ae-2a095b196aa8","title":"Java: Get Number of Elements in a List","slug":"java-get-number-of-elements-in-a-list","body_md":"Getting the number of elements in a list is a common operation during software development. In Java - fetching the length of a list is done via the `size()` method, which accesses the cached length of the list in O(1) lookup time.\n\n## Get Number of Elements in a Java ArrayList\n\n```java\nList\u003cInteger\u003e arrayList = List.of(1, 2, 3);\nSystem.out.println(arrayList.size()); // 3\n```\n\n## Get Number of Elements in Nested List\n\nSometimes though, we have *nested* elements, the wrappers of which can be counted as single elements. Alternatively, their constituent elements could be counted as elements instead. In the former case, the code from the previous section applies, but for the latter case we'd want to sum the sizes of each nested object.\n\nAny object that exposes a method to return its size works - and a `List` implementation such as an `ArrayList` can serve as a complex type in an example. Let's create three lists, and a list containing them and check both the size of the parent list as well as the sum of the sizes of all of the lists:\n\n```java\nList\u003cInteger\u003e list1 = List.of(1, 2, 3);\nList\u003cInteger\u003e list2 = List.of(1, 2, 3);\nList\u003cInteger\u003e list3 = List.of(1, 2, 3);\n\nList\u003cList\u003cInteger\u003e\u003e arrayList = List.of(list1, list2, list3);\nSystem.out.println(arrayList.size()); // 3\n\nint size = arrayList.stream().mapToInt(x -\u003e x.size()).sum();\nSystem.out.println(size); // 9\n```\n\nUsing `mapToInt()` - we can map each element of a stream to an integer value. In our case, we map a stream of three lists into a stream of three integers representing their sizes. Finally, we `sum()` the stream and terminate it - resulting in an `int`.\n\n","body_html":"\u003cp\u003eGetting the number of elements in a list is a common operation during software development. In Java - fetching the length of a list is done via the \u003ccode\u003esize()\u003c/code\u003e method, which accesses the cached length of the list in O(1) lookup time.\u003c/p\u003e\n\u003ch2 id=\"getnumberofelementsinajavaarraylist\"\u003eGet Number of Elements in a Java ArrayList\u003c/h2\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003eList\u0026lt;Integer\u0026gt; arrayList = List.of(\u003cspan class=\"hljs-number\"\u003e1\u003c/span\u003e, \u003cspan class=\"hljs-number\"\u003e2\u003c/span\u003e, \u003cspan class=\"hljs-number\"\u003e3\u003c/span\u003e);\nSystem.out.println(arrayList.size()); \u003cspan class=\"hljs-comment\"\u003e// 3\u003c/span\u003e\n\u003c/code\u003e\u003c/pre\u003e\n\u003ch2 id=\"getnumberofelementsinnestedlist\"\u003eGet Number of Elements in Nested List\u003c/h2\u003e\n\u003cp\u003eSometimes though, we have \u003cem\u003enested\u003c/em\u003e elements, the wrappers of which can be counted as single elements. Alternatively, their constituent elements could be counted as elements instead. In the former case, the code from the previous section applies, but for the latter case we'd want to sum the sizes of each nested object.\u003c/p\u003e\n\u003cp\u003eAny object that exposes a method to return its size works - and a \u003ccode\u003eList\u003c/code\u003e implementation such as an \u003ccode\u003eArrayList\u003c/code\u003e can serve as a complex type in an example. Let's create three lists, and a list containing them and check both the size of the parent list as well as the sum of the sizes of all of the lists:\u003c/p\u003e\n\u003cpre\u003e\u003ccode class=\"hljs\"\u003eList\u0026lt;Integer\u0026gt; list1 = List.of(\u003cspan class=\"hljs-number\"\u003e1\u003c/span\u003e, \u003cspan class=\"hljs-number\"\u003e2\u003c/span\u003e, \u003cspan class=\"hljs-number\"\u003e3\u003c/span\u003e);\nList\u0026lt;Integer\u0026gt; list2 = List.of(\u003cspan class=\"hljs-number\"\u003e1\u003c/span\u003e, \u003cspan class=\"hljs-number\"\u003e2\u003c/span\u003e, \u003cspan class=\"hljs-number\"\u003e3\u003c/span\u003e);\nList\u0026lt;Integer\u0026gt; list3 = List.of(\u003cspan class=\"hljs-number\"\u003e1\u003c/span\u003e, \u003cspan class=\"hljs-number\"\u003e2\u003c/span\u003e, \u003cspan class=\"hljs-number\"\u003e3\u003c/span\u003e);\n\nList\u0026lt;List\u0026lt;Integer\u0026gt;\u0026gt; arrayList = List.of(list1, list2, list3);\nSystem.out.println(arrayList.size()); \u003cspan class=\"hljs-comment\"\u003e// 3\u003c/span\u003e\n\n\u003cspan class=\"hljs-keyword\"\u003eint\u003c/span\u003e size = arrayList.stream().mapToInt(x -\u0026gt; x.size()).sum();\nSystem.out.println(size); \u003cspan class=\"hljs-comment\"\u003e// 9\u003c/span\u003e\n\u003c/code\u003e\u003c/pre\u003e\n\u003cp\u003eUsing \u003ccode\u003emapToInt()\u003c/code\u003e - we can map each element of a stream to an integer value. In our case, we map a stream of three lists into a stream of three integers representing their sizes. Finally, we \u003ccode\u003esum()\u003c/code\u003e the stream and terminate it - resulting in an \u003ccode\u003eint\u003c/code\u003e.\u003c/p\u003e\n","parent_id":null,"type":"byte","status":"published","visibility":"public","img_feature":null,"is_featured":false,"locale":"en","custom_excerpt":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"comment_id":null,"og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":"In this Byte, learn how to get the number of elements in a Java List/ArrayList, both for primitive types and complex types with nested lists of lists.","read_time_min":5,"published_by":16,"published_at":1668598200000,"created_by":16,"updated_by":null,"created_at":1668572404150,"updated_at":1668574253097,"tags":[{"id":13,"name":"java","slug":"java","img_cover":null,"description_md":null,"description_html":"","visibility":"public","og_image":null,"og_title":null,"og_description":null,"twitter_image":null,"twitter_title":null,"twitter_description":null,"meta_title":null,"meta_description":null,"inject_header":null,"inject_footer":null,"canonical_url":null,"color":null,"created_by":null,"updated_by":null,"created_at":1431358735000,"updated_at":1431358735000,"_pivot_content_id":1690,"_pivot_tag_id":13,"_pivot_sort_order":0}],"contributors":[{"id":16,"name":"David Landup","slug":"david","email":"thealduinmaster@gmail.com","password_hash":"$2a$10$W/oMJdUBSTeG3trWAHa1xO0pQruxuLgD/6hS7VuxPafcmAxeBXmVi","role_id":2,"img_profile":"//s3.stackabuse.com/media/users/865cd7d217ea11c9d9555c4f666e2d73.jpg","img_cover":null,"bio_md":"Entrepreneur, Software and Machine Learning Engineer, with a deep fascination towards the application of Computation and Deep Learning in Life Sciences (Bioinformatics, Drug Discovery, Genomics), Neuroscience (Computational Neuroscience), robotics and BCIs. \n\nGreat passion for accessible education and promotion of reason, science, humanism, and progress.","bio_html":"\u003cp\u003eEntrepreneur, Software and Machine Learning Engineer, with a deep fascination towards the application of Computation and Deep Learning in Life Sciences (Bioinformatics, Drug Discovery, Genomics), Neuroscience (Computational Neuroscience), robotics and BCIs.\u003c/p\u003e\n\u003cp\u003eGreat passion for accessible education and promotion of reason, science, humanism, and progress.\u003c/p\u003e\n","website":"https://www.linkedin.com/in/david-landup-859455144/","location":"Serbia","facebook":"","twitter":"","github":null,"status":"inactive","locale":null,"last_seen_at":1622229427000,"created_by":null,"updated_by":1,"created_at":1534532687000,"updated_at":1692629560355,"role":"editor","secret_token":"2a2be92558fae38f89cfbd0c6a4ba90c","is_email_confirmed":true,"plan_name":"free","plan_interval":null,"sub_status":null,"referrer":null,"is_deleted":false,"_pivot_content_id":1690,"_pivot_user_id":16,"_pivot_role":"author","_pivot_sort_order":0}],"_pivot_tag_id":13,"_pivot_content_id":1690}],"content_count":"290"},"page":1,"error":null},"__N_SSP":true},"page":"/tag/[...slug]","query":{"slug":["java"]},"buildId":"1732594514432","isFallback":false,"isExperimentalCompile":false,"gssp":true,"scriptLoader":[]}</script></body></html>

Pages: 1 2 3 4 5 6 7 8 9 10